愛網(wǎng)站長尾推廣營銷策劃方案
開發(fā)新項目過程中 發(fā)現(xiàn)get請求時 數(shù)組參數(shù)沒有下標(biāo)
這樣肯定是不行的 后端接口需要數(shù)組[0]: 7 數(shù)組[1]:4這樣的數(shù)據(jù)
原因是因為在請求攔截器沒有處理需要的參數(shù)
解決方法 在請求攔截器 處理一下參數(shù)
import axios, { AxiosError, AxiosInstance, AxiosRequestHeaders } from "axios";
//request攔截器
service.interceptors.request.use((config) => {///-----------------------這里開始const params = config.params || {};const data = config.data || false;if (config.method?.toUpperCase() === "POST" &&(config.headers as AxiosRequestHeaders)["Content-Type"] ==="application/x-www-form-urlencoded") {config.data = qs.stringify(data);}// get參數(shù)編碼if (config.method?.toUpperCase() === "GET" && params) {let url = config.url + "?";for (const propName of Object.keys(params)) {const value = params[propName];if (value !== void 0 &&value !== null &&typeof value !== "undefined") {if (typeof value === "object") {for (const val of Object.keys(value)) {const params = propName + "[" + val + "]";const subPart = encodeURIComponent(params) + "=";url += subPart + encodeURIComponent(value[val]) + "&";}} else {url += `${propName}=${encodeURIComponent(value)}&`;}}}// 給 get 請求加上時間戳參數(shù),避免從緩存中拿數(shù)據(jù)// const now = new Date().getTime()// params = params.substring(0, url.length - 1) + `?_t=${now}`url = url.slice(0, -1);config.params = {};config.url = url;}///-----------------------這里結(jié)束return config;},(error: AxiosError) => {console.log(error);Promise.reject(error);}
);
加上以后就好了