| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- import axios from 'axios';
- import qs from 'qs';
- /* eslint-disable */
- let baseUrl = process.env.VUE_APP_BASE_URL;
- const axiosInstance = axios.create({
- baseURL: baseUrl
- });
- axiosInstance.interceptors.request.use(
- function (config) {
- config.headers = config.headers || {};
- let token = localStorage.getItem('dianjinToken');
- if (token) {
- config.headers['Authorization'] = 'Bearer ' + token;
- }
- return config;
- },
- function (error) {
- return Promise.reject(error);
- }
- );
- axiosInstance.interceptors.response.use(
- function (response) {
- return response;
- },
- function (error) {
- let errorData = {};
- if (!error.response) {
- errorData = {
- error: '网络错误,请检查网络链接'
- };
- } else {
- errorData = error.response.data;
- // if (401 === error.response.status) {
- // if (router.currentRoute.name !== 'login') {
- // router.replace({
- // name: 'login',
- // params: {
- // from: router.currentRoute.name
- // }
- // });
- // } else {
- // }
- // }
- }
- if (typeof errorData != 'object') {
- errorData = {
- error: '请求失败' + error.response.status
- };
- }
- return Promise.reject(errorData);
- }
- );
- const http = {
- get(url, params) {
- params = params || {};
- return new Promise((resolve, reject) => {
- axiosInstance
- .get(
- url,
- {
- params: params
- },
- {
- withCredentials: true
- }
- )
- .then(res => {
- resolve(res.data);
- })
- .catch(e => {
- reject(e);
- });
- });
- },
- post(url, body, options) {
- options = options || {};
- body = body || {};
- if (!(body instanceof FormData)) {
- if (options.body !== 'json') {
- body = qs.stringify(body);
- }
- }
- return new Promise((resolve, reject) => {
- axiosInstance
- .post(url, body, {
- withCredentials: true
- })
- .then(res => {
- resolve(res.data);
- })
- .catch(e => {
- reject(e);
- });
- });
- }
- };
- export default {
- axios: axiosInstance,
- http: http,
- install(app, options) {
- app.config.globalProperties.$baseUrl = baseUrl;
- app.config.globalProperties.$axios = axiosInstance;
- app.config.globalProperties.$http = http;
- }
- };
|