修改项目目录
在src目录下新建assets, router, redux, styles, utils, views目录
安装axios,并封装
- 安装axios
yarn add axios
- 在utils目录下新建request.js
- 封装axios
import axios from "axios";
import { message } from "antd";
axios.defaults.timeout = 5000;
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;
axios.interceptors.request.use(
(config) => {
config.headers = {
"Content-Type": "application/json",
// "Authorization": ""
};
return config;
},
(error) => {
console.log(error);
return Promise.reject(error);
}
);
axios.interceptors.response.use(
(response) => {
const res = response.data;
if (res.code === 1) {
message.error({
content: res.message,
});
} else {
return res;
}
},
(error) => {
if (
error.response &&
error.response.status !== 400 &&
error.response.status !== 401
) {
message.error({
content:
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message,
});
}
if (error.response && error.response.status === 401) {
message.error({
content: "登录已经失效!",
});
// 处理登录失效 ??
}
if (error.response && error.response.status === 400) {
message.error({
content: error.response.data.message,
});
}
return Promise.reject(error);
}
);
export default {
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
get(url, params) {
return new Promise((resolve, reject) => {
axios
.get(url, {
params: {
...params,
},
})
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
});
},
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
post(url, data) {
return new Promise((resolve, reject) => {
axios
.post(`${url}`, data)
.then((res) => {
resolve(res);
})
.catch((err) => {
reject(err);
});
});
},
/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/
patch(url, data = {}) {
return new Promise((resolve, reject) => {
axios.patch(url, data).then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
});
},
/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/
put(url, data = {}) {
return new Promise((resolve, reject) => {
axios.put(url, data).then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
});
},
/**
* 封装delete请求
* @param url
* @param data
* @returns {Promise}
*/
delete(url, params) {
return new Promise((resolve, reject) => {
axios
.delete(url, {
params: {
...params,
},
})
.then(
(res) => {
resolve(res);
},
(err) => {
reject(err);
}
);
});
},
};
项目配置
在项目根目录新建 .env.development
和 .env.production
文件,配置 REACT_APP_BASE_URL
接口地址:
// .env.development
REACT_APP_BASE_URL = 'http://www.app.test/api'
// .env.production
REACT_APP_BASE_URL = '/api'
网友评论