前言:
請求攔截器可以在我們需要傳遞請求頭的時候使用,例如:token
也會在當token發生變化的時候給予響應,所以我們做好對應的判斷即可
話不多說,直接進入正題:
1.首先在根目錄創建common文件夾,
在里面創建request.js文件并加入以下代碼:
export default {config: {//baseURL這里可以放自己的接口域名baseURL: "",getToken() {//獲取tokenlet token = uni.getStorageSync("userInfo").token;if (!token) {return uni.reLaunch({ url: "/pages/login/login" });}return token;},//獲取useridgetUser() {let id = uni.getStorageSync("userInfo").id;if (!id) {return uni.reLaunch({ url: "/pages/login/login" });}return id;},// 響應攔截器beforeRequest(options = {}) {return new Promise((resolve, reject) => {//請求的地址 = 上面設置的域名加上接口封裝的地址options.url = this.baseURL + options.url;options.method = options.method || "POST";//添加請求頭options.header = {token: this.getToken(),id: this.getUser(),};resolve(options);});},// 請求攔截器handleResponse(data) {//自行打印data根據data里的數據進行判斷token過期等等if (data.data.code == 0 && data.data.msg == "權限錯誤"){uni.showModal({title: '提示',content: '已掉線,是否重新登錄',showCancel: true,success: ({ confirm, cancel }) => {if(confirm){uni.redirectTo({ url: '/pages/login/login' })}else{}}})}return data;},},// request 請求request(options = {}) {return this.config.beforeRequest(options).then((opt) => {return uni.request(opt);}).then((res) => this.config.handleResponse(res));},
};
2,在common文件夾下接著新建一個example.js文件來當作接口封裝的文件
// api/example.js
import api from "@/common/request.js";
//把我們剛才寫的request.js文件引入過來
export function pubdemo(data) {console.log(data, "傳遞的參數");//使用引入的request發送請求return api.request({//request.js文件里面已經有前綴了所以這里直接寫后面的路徑即可url: "/api/web/Notice/reminder",method: "post",data: data,});
}
3,頁面內使用
import { pubdemo } from "@/common/example.js";pubdemo({//這里是要傳遞的參數,前面參數名后面參數值id: 12,}).then((res) => {console.log(res.data,res.data);});
對于一些不用傳遞參數的接口直接把變量名里面的對象刪除即可
pubdemo().then((res) => {console.log(res.data,res.data);});
微信小程序
微信小程序跟uniapp同理,只需要把某些東西改一下即可
創作不易,留下免費的雙擊關注再走吧~