uniapp 二次封装插件--luch-request的使用
2022-04-28 本文已影响0人
autumn_3d55
1. uni.request 二次封装插件-luch-request
1下载
npm i luch-request -S
2.使用
- vue.config.js
module.exports = {
transpileDependencies: ["@dcloudio/uni-ui", "luch-request"],
}
- 1 request.js 封装请求拦截
在src下创建一个 utils文件夹,在utils 文件夹下创建 request.js文件
import Request 'luch-request'
const BASE_API = 'http://127.0.0.1'
const http = new Request({
baseURL: BASE_API, //设置请求的base url
timeout: 300000, //超时时长5分钟,
header: {
'Content-Type': 'multipart/form-data;application/json;charset=UTF-8;'
}
})
//请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
const token = uni.getStorageSync('token');
if (token) {
config.header={
"Authorization":'Bearer ' + token
}
}
if (config.method === 'POST') {
config.data = JSON.stringify(config.data);
}
return config
}, error => {
return Promise.resolve(error)
})
// 响应拦截器
http.interceptors.response.use((response) => {
console.log(response)
return response
}, (error) => {
//未登录时清空缓存跳转
if (error.statusCode == 401) {
uni.clearStorageSync();
uni.switchTab({
url: "/pages/index/index.vue"
})
}
return Promise.resolve(error)
})
export default http;
- 2 api 接口封装
在src下创建一个 api文件夹,在api文件夹下创建 index.js文件
- index.js
import http from '@/utils/http'
// 列表查询:
export function getList(data) {
return http.request({
url: '/index/getList',
method: 'post',
data
})
}
- 3 在页面中使用
- index.vue
import {
getList,
} from "@/api/index";
// 列表查询
getList() {
this.getList()
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log("查询错误", err);
});
},