1.在集成终端打开,使用 npm 安装 Axios
npm install axios --save
2.在src录下创建utils文件夹,并创建request.ts文件
3.对axios进行封装
import axios from 'axios';
import { Toast } from 'vant';
let baseURL = '/api';
const service = axios.create({
baseURL,
timeout: 10000,
});
//发起请求之前的拦截器
service.interceptors.request.use(
(config: any) => {
const token = window.localStorage.getItem('token');
if (token) {
config.headers = {
token: token,
};
}
return config;
},
error => {
return Promise.reject(error);
}
);
//响应拦截器
service.interceptors.response.use(
(response: any) => {
const res = response.data;
if (response.status !== 200) {
return Promise.reject(new Error(res.sucess || 'Error'));
} else {
if (res.code == 200) {
return res.result;
} else {
Toast(res.sucess);
}
}
},
error => {
return Promise.reject(error);
}
);
export default service;
4.在vite.config.ts配置代理
server: {
port: 8002,
host: '0.0.0.0',
open: true,
proxy: {
'/api': '接口地址',
},
cors: true,
},
5.api接口模块
import request from '../utils/request';
//获取验证码
export function getCode(data: any) {
return request({
url: '/login/code',
method: 'post',
data,
});
}