設(shè)置反向代理
1、安裝依賴npm install http-proxy-middleware --save-dev
2弦撩、在src目錄中創(chuàng)建一個名為setupProxy.ts的文件
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: '后端api地址',
changeOrigin: true,
})
);
};
3昨稼、在index.tsx中引入
import './setupProxy';
封裝axios
1节视、安裝依賴yarn add axios
2、創(chuàng)建requset.ts文件
import axios from "axios"
// 創(chuàng)建axios實例
const instance = axios.create({
baseURL: '可設(shè)置為反向代理地址',
timeout: 1000,
});
// 添加請求攔截器
let token = localStorage.getItem("token")
axios.interceptors.request.use(function (config) {
if (token) {
config.headers.token = token
}
// 在發(fā)送請求之前做些什么
return config;
}, function (error) {
// 對請求錯誤做些什么
console.log(error)
return Promise.reject(error);
});
// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response: any) {
// 對響應(yīng)數(shù)據(jù)做點什么
if (response.code === 200) {
return response
} else {
console.error(response.message || response.msg)
}
return response;
}, function (error) {
// 對響應(yīng)錯誤做點什么
let text = "";
if (error.response.status) {
switch (error.response.status) {
case 400:
text = "請求錯誤(400)假栓,請重新申請";
break;
case 401:
text = "登錄錯誤(401)寻行,請重新登錄";
break;
case 403:
text = "拒絕訪問(403)";
break;
case 404:
text = "請求出錯(404)";
break;
case 408:
text = "請求超時(408)";
break;
case 500:
text = "服務(wù)器錯誤(500),請重啟軟件或切換功能頁匾荆!";
break;
case 501:
text = "服務(wù)未實現(xiàn)(501)";
break;
case 502:
text = "網(wǎng)絡(luò)錯誤(502)";
break;
case 503:
text = "服務(wù)不可用(503)";
break;
case 504:
text = "網(wǎng)絡(luò)超時(504)";
break;
case 505:
text = "HTTP版本不受支持(505)";
break;
default:
text = "網(wǎng)絡(luò)連接出錯";
}
} else {
text = "連接服務(wù)器失敗,請退出重試!";
}
console.error(text)
return Promise.reject(error);
});
export default instance
3拌蜘、創(chuàng)建api.ts文件
import instance from "@/utils/requset";
// 用戶登錄
export const Login = (params: any) => {
return instance.request({
url: "",
method: "GET",
params
});
};
// 用戶注冊
export const userRegister = (data) => {
return instance.request({
url: "",
method: "POST",
data
});
};
4、頁面使用
import { login} from "@/api/index"
login().then(res => {}).catch(error=>{})