安装
cmd:
yarn add luch-request
main.js中:
import Request from 'luch-request' //yarn
Vue.prototype.$http = new Request({
// 全局配置
baseURL: BaseUrl,
header: {
/* 这个地方每次都调用 */
"X-Access-Token": uni.getStorageSync('token')
},
method: 'GET',
dataType: 'json',
// #ifndef MP-ALIPAY
responseType: 'text',
// #endif
// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
custom: {}, // 全局自定义参数默认值
// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
timeout: 60000,
// #endif
// #ifdef APP-PLUS
sslVerify: true,
// #endif
// #ifdef H5
// 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
withCredentials: false,
// #endif
// #ifdef APP-PLUS
firstIpv4: ture, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
// #endif
// 局部优先级高于全局,返回当前请求的task,options。请勿在此处修改options。非必填
// getTask: (task, options) => {
// 相当于设置了请求超时时间500ms
// setTimeout(() => {
// task.abort()
// }, 500)
// },
// 全局自定义验证器。参数为statusCode 且必存在,不用判断空情况。
validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置
return statusCode >= 200 && statusCode < 300
}
});
// 示例:this.$http.get("url",param:{a:1,b:2}).then(()=>{}).catch(err=>{})
// 传json字符串this.$http.post('url',{a:"1",b:"2"}}).then(()=>{}).catch(err=>{})
// 传form-data表单this.$http.post('url',{a:"1",b:"2"},{header: {"content-type":"application/x-www-form-urlencoded"}}).then(()=>{}).catch(err=>{})
// 帮助:https://ext.dcloud.net.cn/plugin?id=392
// 详见https://www.quanzhan.co/archives/251 问题8
使用:
get:
this.$http.get("url",param:{a:1,b:2}).then(()=>{}).catch(err=>{})
post:
this.$http.post('url',{a:"1",b:"2"}}).then(()=>{}).catch(err=>{})
使用form-data表单进行post(使用form表单post)
this.$http.post('url',{a:"1",b:"2"},{header: {"content-type":"application/x-www-form-urlencoded"}}).then(()=>{}).catch(err=>{})
完整示例:
this.$http.post('/index/url',form)
.then(res => {
if (res.data.success) {
console.log(res.data.result);
//业务逻辑
} else {
uni.showToast({
icon: 'none',
title: '发起失败,请联系管理员!',
duration: 2000
})
console.log(res);
}
}).catch(err => {
uni.showToast({
icon: 'none',
title: '发起失败,请联系管理员!',
duration: 2000
})
console.log(err);
})
说明
官网:
https://ext.dcloud.net.cn/plugin?id=392
踩坑:
https://www.quanzhan.co/archives/251