uniapp二次封装请求
在manifest.json文件中定义开发模式下的跨域链接
加入以下代码
"h5":{
"devServer": {
"proxy": {
"/api": {
"target": "后台地址",
"changeOrigin": true,
"secure": false,
"pathRewrite":{"^/api":""}
}
}
}
}
可在main.js中全局定义,也可单个文件引入。
全局定义:
import { myRequest } from './api/api.js'
Vue.prototype.$rq = myRequest
定义方法:
export const myRequest=(options)=>{ //传入的options是一个json对象
return new Promise((resolve,reject)=>{
uni.request({
url:'/api' + options.url,
method:options.methods||"GET", // 从options取出请求方法
header: options.methods+'' == 'post'?{'content-type': 'application/x-www-form-urlencoded' }:"", // 如果请求方法是post 则加入请求头否则为空 post方法加请求头为序化传递参数
data:options.data || {}, // 从options对象中取出数据
dataType:options.dataType || "json",
success: (res) => {
resolve(res.data)
} // 不需要传失败的回调,仅判断成功回调就可以完成。
})
})
}
使用方式:
ES7的 Async Await 没有加try catch 自行补上
async datas(){
let params = {id:123}
const res = await this.$rq({
url:'/shopping/info',
// header:{'content-type': 'application/x-www-form-urlencoded' },//自定义请求头信息
methods:'post',
data:params
})
console.log(res)
}