1、创建一个json数据到根目录mock.json
{
"products": [
{ "id": 1, "name": "产品 A" },
{ "id": 2, "name": "产品 B" },
{ "id": 3, "name": "产品 C" }
]
}
2、更新api封装地址:
baseURL: 'http://localhost:3000'api文件如下:import axios from 'axios';
// 创建 Axios 实例
const apiClient = axios.create({
baseURL: 'http://localhost:3000', // 更改地址
timeout: 10000, // 超时时间
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器
apiClient.interceptors.request.use(
(config) => {
// 在请求发送之前做些什么,例如添加 token
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
(error) => {
// 处理请求错误
return Promise.reject(error);
}
);
// 响应拦截器
apiClient.interceptors.response.use(
(response) => {
// 统一处理返回数据
return response.data; // 直接返回数据
},
(error) => {
// 处理错误
const { response } = error;
if (response) {
// 根据 HTTP 状态码处理不同的错误
switch (response.status) {
case 401:
alert('未授权,请登录!');
break;
case 404:
alert('请求的资源未找到!');
break;
case 500:
alert('服务器错误,请稍后再试!');
break;
default:
alert('发生错误,请重试!');
}
} else {
alert('网络错误,请检查您的网络连接!');
}
return Promise.reject(error);
}
);
// 封装请求方法
const api = {
get: (url, params) => apiClient.get(url, { params }),
post: (url, data) => apiClient.post(url, data),
put: (url, data) => apiClient.put(url, data),
delete: (url) => apiClient.delete(url),
};
export default api;
3、运行:
在项目根目录下,使用以下命令启动 json-server:
npx json-server --watch mock.json --port 3000
启动项目:
npm start