85 lines
2.0 KiB
JavaScript
Raw Normal View History

2022-08-02 10:16:07 +08:00
/*
* @Description: api请求
* @Author: chenzhiwei (725551805@qq.com)
* @Date: 2021-08-02 15:52:34
* @LastEditors: czw (725551805@qq.com)
* @LastEditTime: 2022-03-13 11:05:08
* @FilePath: /glxt/src/util/http.js
*/
2022-08-12 18:26:27 +08:00
import axios from "axios";
import { getToken } from "@/util/auth";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Message } from "element-ui";
import router from "@/router";
2022-08-02 10:16:07 +08:00
var instance = axios.create({
2022-08-12 18:26:27 +08:00
timeout: 10000,
});
2022-08-02 10:16:07 +08:00
instance.interceptors.request.use(
2022-08-12 18:26:27 +08:00
(config) => {
2022-08-02 10:16:07 +08:00
// config.headers['content-type'] = 'application/json'
// config.headers['Shop-Id'] = localStorage.getItem('shopId') || 1
// 在发送请求之前做些什么
2022-08-12 18:26:27 +08:00
// config.headers.Authorization = "Bearer" + getToken(); // 请求头
2022-08-02 10:16:07 +08:00
// config.headers['content-type'] = 'application/json'
2022-08-12 18:26:27 +08:00
config.headers.Authorization = "Bearer " + getToken(); // 请求头
NProgress.start();
2022-08-06 20:03:35 +08:00
// console.log(config, '1111') // for debug
2022-08-02 10:16:07 +08:00
2022-08-12 18:26:27 +08:00
return config;
2022-08-02 10:16:07 +08:00
},
2022-08-12 18:26:27 +08:00
(error) => {
2022-08-02 10:16:07 +08:00
// 对请求错误做些什么
2022-08-12 18:26:27 +08:00
console.log(error, "222222"); // for debug
return Promise.reject(error);
2022-08-02 10:16:07 +08:00
}
2022-08-12 18:26:27 +08:00
);
2022-08-02 10:16:07 +08:00
// 添加响应拦截器
instance.interceptors.response.use(
2022-08-12 18:26:27 +08:00
(response) => {
NProgress.done();
const res = response.status;
2022-08-02 10:16:07 +08:00
// 对响应数据做点什么
2022-08-06 20:03:35 +08:00
// console.log(response, '33333') // for debug
2022-08-02 10:16:07 +08:00
if (res === 200 || res === 201) {
2022-08-12 18:26:27 +08:00
return response;
2022-08-02 10:16:07 +08:00
} else {
Message({
2022-08-12 18:26:27 +08:00
message: "Error",
type: "error",
});
2022-08-02 10:16:07 +08:00
}
},
2022-08-12 18:26:27 +08:00
(error) => {
2022-08-17 15:40:04 +08:00
console.log(error);
2022-08-02 10:16:07 +08:00
// 对响应错误做点什么
2022-08-12 18:26:27 +08:00
Message({
message: error,
type: "error",
});
2022-08-17 15:40:04 +08:00
// console.log(error, "44444"); // for debug
2022-08-02 10:16:07 +08:00
// if (error.response.status === 401) {
// Message({
// message: '账户登录过期,请重新登录',
// type: 'error'
// })
// router.push('/login')
// } else {
// Message({
// message: error.response || 'Error',
// type: 'error'
// })
// }
2022-08-12 18:26:27 +08:00
return Promise.reject(error);
2022-08-02 10:16:07 +08:00
}
2022-08-12 18:26:27 +08:00
);
2022-08-02 10:16:07 +08:00
2022-08-12 18:26:27 +08:00
export default instance;