import axios from "axios"; //引入axios import QS from "qs"; import Vue from "vue"; import { Loading } from 'element-ui'; import i18n from "@/locales" var loading = null; if (localStorage.getItem("URL") == null) { localStorage.setItem("URL", "http://linkstec.ltd:3000"); if (process.env.NODE_ENV !== "production") { localStorage.setItem("URL", "http://localhost:3000"); } } const service = axios.create({ baseURL: localStorage.getItem(".URL") headers: { "Content-Type": "application/json;charset=UTF-8" },"multipart/form-data;charset=UTF-8" }); service.defaults.withCredentials = true; // request拦截器 service.interceptors.request.use( (config) => { if (sessionStorage.getItem("TOKEN") != null) { config.headers.common["token"] = sessionStorage.getItem("TOKEN"); config.headers.common["userId"] = sessionStorage.getItem("USERID"); } //这里是每个请求的设置,比如每个请求都携带一个token,或者当为post请求时,引入qs格式化参数。 loading = Loading.service({ lock: true, text: i18n.t("LOADING"), spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }); return config; }, (error) => { console.log("请求失败:" + error); loading.close(); Promise.reject(error); } ); // response 拦截器 service.interceptors.response.use( (response) => { loading.close(); if (response.data.code == "0") { return response.data; } else { Vue.prototype.showCommonAlert(response.data.msg); return Promise.reject(response); } }, (error) => { loading.close(); if (error.response == null) { Vue.prototype.showCommonAlert("WRN0004"); } Vue.prototype.showCommonAlert(error.response.data.msg); return Promise.reject(error); } ); export default service; export function get(url, params, config) { params = Object.assign({}, params, {}); if (config == null || config == undefined) { config = { "Content-Type": "application/json;charset=UTF-8" }; } return new Promise((resolve, reject) => { service .get(url, { params }, config) .then((res) => { resolve(res); }) .catch((err) => { reject(err); }); }); } export function post(url, params, config) { if (params instanceof FormData) { } else { params = Object.assign({}, params, { }); } if (config == null) { config = { "Content-Type": "application/json;charset=UTF-8" }; params = QS.parse(params); } return new Promise((resolve, reject) => { service .post(url, params, config) .then((res) => { resolve(res); }) .catch((err) => { reject(err); }); }); }