uniapp项目搭建 请求配置
每个人项目用的请求接口不一样,这里就看下实现思路就好了
请求配置
在 uniapp 当中有封装好的 request 插件, request插件地址
在项目的 utils/request/index.js 中是对请求的配置
utils/request/index.js代码
/**
* request插件地址:https://ext.dcloud.net.cn/plugin?id=822
*/
import store from '@/store'
import request from './request'
import Config from '@/core/config'
// 后端api地址
const apiUrl = Config.get('apiUrl')
// 可以new多个request来支持多个域名请求
const $http = new request({
// 接口请求地址
baseUrl: apiUrl,
// 服务器本地上传文件地址
fileUrl: apiUrl,
// 服务器上传图片默认url
defaultUploadUrl: 'upload/image',
// 设置请求头(如果使用报错跨域问题,可能是content-type请求类型和后台那边设置的不一致)
header: {
'content-type': 'application/json;charset=utf-8'
},
// 请求超时时间, 单位ms(默认15000)
timeout: 15000,
// 默认配置(可不写)
config: {
// 是否自动提示错误
isPrompt: true,
// 是否显示加载动画
load: true,
// 是否使用数据工厂
isFactory: true
}
})
// 当前接口请求数
let requestNum = 0
// 请求开始拦截器
$http.requestStart = options => {
if (options.load) {
if (requestNum <= 0) {
// 打开加载动画
uni.showLoading({
title: '加载中',
mask: true
})
}
requestNum += 1
}
// 图片上传大小限制
if (options.method == "FILE" && options.maxSize) {
// 文件最大字节: options.maxSize 可以在调用方法的时候加入参数
const maxSize = options.maxSize
for (let item of options.files) {
if (item.size > maxSize) {
setTimeout(() => {
uni.showToast({
title: "图片过大,请重新上传",
icon: "none"
})

本文介绍UniApp项目中的请求配置方法及接口调用流程。通过分析`utils/request/index.js`文件,展示了如何配置请求插件、处理请求与响应、编写及调用接口。适合初学者学习。
最低0.47元/天 解锁文章
1411

被折叠的 条评论
为什么被折叠?



