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下創(chuàng)建一個 utils文件夾虏等,在utils 文件夾下創(chuàng)建 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) => {
//未登錄時清空緩存跳轉(zhuǎn)
if (error.statusCode == 401) {
uni.clearStorageSync();
uni.switchTab({
url: "/pages/index/index.vue"
})
}
return Promise.resolve(error)
})
export default http;
- 2 api 接口封裝
在src下創(chuàng)建一個 api文件夾伦连,在api文件夾下創(chuàng)建 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);
});
},