The requirements of each project vary, so be sure to adjust the configuration for your own project

If you have any good suggestions, you can reply in the comment section!

1. Create the Httpload. js file


import axios from 'axios';
import {
    Message,
    Loading
} from 'element-ui';
import router from '.. /router';
import _ from 'lodash';
import qs from 'qs';

const http = axios.create({
    baseURL: process.env.API_HOST, // Set the base URL for the request
    timeout: 300000.// The timeout duration is 5 minutes,
    crossDomain: true
});

http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8; multipart/form-data'
// It is not necessary to use this method based on specific requirements
http.defaults.paramsSerializer = (params) = > {
    return qs.stringify(params, {
        arrayFormat: 'brackets'
    });
}
/ / loading object
let loading;

// The number of requests currently being made
let needLoadingRequestCount = 0;

/ / display loading
function showLoading(target) {
    // This is important because the loading object may still exist when the loading object is closed.
    // But needLoadingRequestCount has become 0. Avoid creating a loading again in this case
    if (needLoadingRequestCount === 0 && !loading) {
        loading = Loading.service({
            lock: true.text: "Loading like crazy...".background: 'rgba (255, 255, 255, 0.5)'.target: target || "body"
        });
    }
    needLoadingRequestCount++;
}

/ / hide loading
function hideLoading() {
    needLoadingRequestCount--;
    needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // Make a protection
    if (needLoadingRequestCount === 0) {
        / / close the loadingtoHideLoading(); }}// Anti-vibration: merge the shutdown loading within 300ms into a single loading. Prevent loading flashing during continuous requests.
var toHideLoading = _.debounce(() = > {
    if(loading ! =null) {
        loading.close();
    }
    loading = null;
}, 300);

// Add request interceptor
http.interceptors.request.use(config= > {
    // Check whether the current request is not loaded
    if(config.headers.showLoading ! = =false) {
        showLoading(config.headers.loadingTarget);
    }
    config.url = decodeURI(encodeURI(config.url).replace('%E2%80%8B'."")) // Remove whitespace from the URL
    // It is not necessary to use this method based on specific requirements
    if (config.method === 'post') {
        config.data = qs.stringify(config.data);
    }

    const token = sessionStorage.token;
    if (token) {
        config.headers.common["Authorization"] = 'Bearer' + token;
    }
    return config;
}, err= > {
    // Check whether the current request is not loaded
    if(config.headers.showLoading ! = =false) {
        hideLoading();
    }
    Message.error('Request timed out! ');
    return Promise.resolve(err);
});

// Response interceptor
http.interceptors.response.use(
    response= > {
        // Check whether the current request is not loaded.
        if(response.config.headers.showLoading ! = =false) {
            hideLoading();
        }
     // If you need to refresh the token, you can release the following code
    //if (response.status === 401) {
      //refreshTokenFuc(isRefreshToken, config, retryRequests);
     // return Promise.reject(response);
   // }
	return response;
    },
    error= > {
        // Check whether the current request is not loaded.
        // if (error.config.headers.showLoading ! == false) {
        hideLoading();
        // }
		if(error.response&&error.response.status){
			switch (error.response.status) {
				//401: Not logged in - Authorization expired
				case 401:
				// Operations performed when the authorization expires, such as returning to the login page
				
				// If you need to refresh the token, you can release the following code
				//var config=error.config;
				//refreshTokenFuc(isRefreshToken, config, retryRequests);
				break;
			}
			return Promise.reject(error.response);
		}

        // if(error.response && error.response.data && error.response.data.message) {
        // var jsonObj = JSON.parse(error.response.data.message);
        // Message.error(jsonObj.message);
        // }else{
        // Message.error(error.message);
        // }// if (error.response.status) {
        // switch (error.response.status) {
        // // 401: Not logged in
        // // If you do not log in, the login page is displayed and the path of the current page is displayed
        // // Return to the current page after successful login. This step must be performed on the login page.
        // case 401:
        // router.replace({
        // path: '/login',
        // query: { redirect: router.currentRoute.fullPath }
        / /})
        // break
        // // 403 Token expires
        // // Prompts users about login expiration
        // // Clear local tokens and vuEX token objects
        // // The login page is displayed
        // case 403:
        // message. error(' Login expired, please login again! ');
        // // Clearing a Token
        // localStorage.removeItem('token')
        // store.commit('loginSuccess', null)
        // // Redirect to the login page and upload the fullPath of the page to be accessed. After the login is successful, redirect to the page to be accessed
        // setTimeout(() => {
        // router.replace({
        // path: '/login',
        // query: {
        // redirect: router.currentRoute.fullPath
        / /}
        / /})
        / /}, 1000)
        // break
        The // // 404 request does not exist
        // case 404:
        // message. error(' Network request does not exist ');
        // break
        // // For other errors, an error message is displayed
        // default:
        // Message.error(error.response.data.message);
        / /}
        // return Promise.reject(error.response)
        / /}
        return Promise.reject(error); });export default http;


Copy the code

2. Create an API folder and place the following code in index.js

The API is packaged and exported for use on the page

import request from "@/http/httpload.js"
	export default{
		getData(data){
		return request({
			url:"/api/xxx".method:"post".data:data
		})
    },
    getManyData(data){
		return request({
			url:"/api/xxx".method:"get".parmas:data
		})
	}
}
Copy the code

3. On the VUE page

<template>
  <div>
    <el-button class="el-icon-user" @click="getData">To get the data</el-button>
  </div>
</template>
<script>
import Task from "@/api/index.js";
export default {
  name: "testDemo".methods: {
    getData() {
      var data={id:'xxxxxxx'}
      Task.getData(data).then(res= > {
         console.log(res);
      }).catch(error= >{
        console.log(error); }); }}};</script>
Copy the code

4. Refresh the refreshToken code [optional, use as required]

If you need to refresh the token, put the following code into the httpload.js file:

Note: The following code must precede the response to an interception request

Problem to be solved: After refreshing the refreshToken, the new Token can be obtained normally, and the previous incorrect request is automatically requested again. The data returned is normal, but the page will not be re-rendered, because the data request has been caught! Currently there is no good solution, users need to click any button on the page or refresh the page

let isRefreshToken = false;// Whether the token is being refreshed
let retryRequests = []; // An array to store error requests
// Refresh the token method
function refreshTokenFuc(isRefreshToken, config, retryRequests) {
  if(! isRefreshToken) { isRefreshToken =true;
    var data = { refreshtoken: sessionStorage.refreshtoken }
    //TokenApi is a self-encapsulated AXIos network request, which can be replaced by your own request for the backend refresh token
    TokenApi.refreshToken(data).then(res= > {
      sessionStorage.token = res.data.data.token.access_token;
      sessionStorage.refreshtoken = res.data.data.token.refresh_token;
      config.headers["Authorization"] = 'Bearer ' + res.data.data.token.access_token;
      retryRequests.forEach((cb) = > cb(res.data.data.token.access_token));
      retryRequests = [];
      return http.request(config);
    }).catch(error= > {
      message.error("Authentication failed, please log in again!");
      sessionStorage.clear();
      setTimeout(() = > {
        router.replace({
          path: '/login'.// query: { redirect: router.currentRoute.fullPath }})},1500)
    }).finally(() = > {
      isRefreshToken = false; })}else {
   // Store the incorrect request and re-initiate the request after refreshing the token
    return new Promise((resolve) = > {
      retryRequests.push((token) = > {
        config.headers["Authorization"] = 'Bearer ' + token;
        resolve(http.request(config))
      })
    })
  }
}

Copy the code