luch-request简易配置
luch-request-uni应用市场地址: 应用市场
从应用市场下载后 目录为 js_sdk
在根目录新建 utils 目录 将下载在 js_sdk 下的 luch-request目录 复制到新建的 utils 目录
在根目录新建 config 目录并新建 common.js 文件内容如下
import Request from '@/utils/luch-request/index.js'
const http = new Request()
export {http}
http.setConfig((config) => { /* config 为默认全局配置*/
config.baseURL = 'http://location'; /* 根域名 */
config.header = {
'content-type':'application/x-www-form-urlencoded'
}
return config
})
//请求前拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
config.header = {
...config.header,
}
//获取存储的token
const token = uni.getStorageSync('token');
config.header.token=token;
return config
}, config => { // 可使用async await 做异步操作
return Promise.reject(config)
})
// 请求后拦截器
http.interceptors.response.use((response) => {
return response
}, (response) => {
//未登录时清空缓存跳转
if(response.statusCode ==401){
uni.clearStorageSync();
uni.navigateTo({
url:"/pages/login/wechat"
})
}
return Promise.reject(response)
})
创建完成后在main.js文件 引入 common.js 全局配置
import { http,api } from '@/config/common.js' // 全局挂载引入,配置相关在该index.js文件里修改
Vue.prototype.$http = http
Vue.prototype.$api = api
此时已完成配置调用
this.$http.post('api/index/baseconfig', {
'id':123
} ).then(res => {
console.log(res);
}).catch(err => {
})
具体请求实例请参考 官方文档
路易拉菲