123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- import axios from 'axios';
- import store from '@/store';
- import router from '@/router';
- import { getToken } from '@/utils/auth';
- import { Message } from 'element-ui';
- const service = axios.create({
- baseURL: process.env.VUE_APP_BASE_API,
- timeout: 30000,
- });
- // 请求拦截器
- service.interceptors.request.use(
- (config) => {
- config.headers['Content-Type'] = 'application/json';
- return config;
- },
- (error) => {
- return Promise.reject(error);
- },
- );
- // 响应拦截器
- service.interceptors.response.use(
- (response) => {
- const res = response.data;
- const { code, status, message, error } = res;
- if (code === 404) {
- Message({
- message: '请求的资源不存在',
- type: 'error',
- duration: 3 * 1000,
- });
- return Promise.reject(new Error(message || 'Error'));
- }
- // 返回数据失败
- if (status === 0) {
- Message({
- message: `${error}`,
- type: 'error',
- duration: 3 * 1000,
- });
- return Promise.reject(new Error(`${error}` || 'Error'));
- }
- // 无效的操作用户
- if (status === -1) {
- Message({
- message: error,
- type: 'error',
- duration: 3 * 1000,
- });
- store.dispatch('user/signOut');
- router.push('/login');
- }
- return res;
- },
- (error) => {
- if (error.code === 'ERR_CANCELED') {
- return Message.success('取消上传成功');
- }
- Message({
- message: error.message,
- type: 'error',
- duration: 3 * 1000,
- });
- return Promise.reject(error);
- },
- );
- /**
- * 得到必需的请求参数
- * @returns {object} 返回必需的请求参数
- * */
- function getRequestParams() {
- const token = getToken();
- return {
- AccessToken: token?.access_token ?? '',
- UserCode: token?.user_code ?? '',
- UserType: token?.user_type ?? '',
- SessionID: token?.session_id ?? '',
- };
- }
- /**
- * @description http 请求封装
- */
- export const http = {
- /**
- * @param {String} url 请求地址
- * @param {object} config 请求配置
- */
- get: (url, config) => service.get(url, config),
- /**
- * @param {string} url 请求地址
- * @param {object} data 请求数据
- * @param {object} config 请求配置
- */
- post: (url, data = {}, config = {}) => {
- config.params = {
- ...config.params,
- ...getRequestParams(),
- };
- return service.post(url, data, config);
- },
- postForm: (url, data = {}, config = {}) => {
- config.params = {
- ...config.params,
- ...getRequestParams(),
- };
- return service.postForm(url, data, config);
- },
- put: (url, data, config) => service.put(url, data, config),
- delete: (url, data, config) => service.delete(url, data, config),
- };
|