SoFunction
Updated on 2025-04-04

Detailed explanation of the configuration steps of dynamic Axios

Preface

In the past, when I wrote Vue projects, I used vue-resource as the project ajax library. One day in November, Youda Weibo updated it on Weibo that ajax library should be universal, and gave up the technical support for vue-resource and recommended to use axios.

It is recommended to use the Vue-cli tool to create and manage projects. Even if you are not familiar with it at the beginning, you will know the mystery after using it. The data request plug-in officially recommended by the official some time ago is Vue-resource, but now it has changed, and it has become Axios. You don’t need to know why it has changed. Anyway, this one is better than that, just use it. Here are some experiences about encapsulating axios requests. If it is wrong, I hope you will give me some advice!

The method is as follows

1. Create a file. After the Vue project is initialized, create an util tool folder in the src directory. It is generally used to store some encapsulated function methods. Now let us create a file in the util file directory to encapsulate the axios method.

2. Directly upload the code (regular version), with detailed comments in the code

import axios from 'axios' //Quoting axiosimport {Promise} from 'es6-promise' //Introduce Promise// axios configuration = 5000; //Set the timeout time = 'http://localhost:4000/api/v1/'; //This is calling the data interface// http request interceptor (all sent requests must be passed from here once). Through this, we can pass the token to the background. I am using sessionStorage to store permission information and user information such as token. If you want to use cookies, you can encapsulate a function and import it to use it.(
 config => {
  const token = ("token"); //Get the token stored locally   = ();
   = {
   'Content-Type':'application/json' //Set cross-domain headers. Although many browsers use json to transmit data by default, we need to consider IE browser.  };
  if (token) {
    = "Token " + token; //Permission parameters  }
  return config;
 },
 err => {
  return (err);
 }
);


// http response interceptor (all received requests must be passed from here once)(
 response => {
//===401 is the status code that I agreed with the background and the status code that I lost or the permissions were insufficient. This can be agreed with the background myself, and it is also OK to return a custom field.  if( == 401) {
   ({ //After push is a parameter object, which can carry many parameters. You can check it on vue-router, for example, the query field represents the parameters carried by it.    path: '/login' 
   })
  }
  return response;
 },
 error => {
  return ()
 });

export default axios;

/**
  * fetch request method
  * @param url
  * @param params
  * @returns {Promise}
  */
export function fetch(url, params = {}) {
 return new Promise((resolve, reject) => {
  (url, {
   params: params
  })
  .then(response => {
   resolve();
  })
  .catch(err => {
   reject(err)
  })
 })
}

/**
  * post request method
  * @param url
  * @param data
  * @returns {Promise}
  */
export function post(url, data = {}) {
 return new Promise((resolve, reject) => {
  (url, data)
   .then(response => {
    resolve();
   }, err => {
    reject(err);
   })
 })
}

/**
  * patch method encapsulation
  * @param url
  * @param data
  * @returns {Promise}
  */
export function patch(url, data = {}) {
 return new Promise((resolve, reject) => {
  (url, data)
   .then(response => {
    resolve();
   }, err => {
    reject(err);
   })
 })
}

/**
  * put method encapsulation
  * @param url
  * @param data
  * @returns {Promise}
  */
export function put(url, data = {}) {
 return new Promise((resolve, reject) => {
  (url, data)
   .then(response => {
    resolve();
   }, err => {
    reject(err);
   })
 })
}

3. (Dynamic Version), the interceptor of axios is not necessary, not every project needs it, and there is more than one Content-Type and Authorization in headers, so another method needs to be used.

util/

import axios from 'axios' //Quoting axiosimport {Promise} from 'es6-promise' //Introduce Promise// Axios configuration and interceptor are not used. Here I use a dynamic configuration data request address. In the code below, this is not necessary.//^_^The default header is set below. When using it, you can pass in data to overwrite ^_^. For example, when using the fetch(GET) method, there is no request data, but the request header changes, it should be written as fetch("address", {}, {"write the content of the header here"}) Remember that no data takes up the position with an empty object./**
  * fetch request method
  * @param url
  * @param params
  * @returns {Promise}
  */
export function fetch(url, params = {}, headers = {
 'Content-Type': 'application/json', //Set cross-domain header "Authorization": 'JWT ' + ("authToken")
}) {

 return new Promise((resolve, reject) => {
  (url, {
   params: params,
   headers: headers
  })
  .then(response => {
   resolve();
  })
  .catch(err => {
   reject()
  })
 })
}

/**
  * post request method
  * @param url
  * @param data
  * @returns {Promise}
  */
export function post(url, data = {}, config = {
 "headers": {
  'Content-Type': 'application/json', //Set cross-domain header  "Authorization": 'JWT ' + ("authToken")
 }
}) {
 return new Promise((resolve, reject) => {
  (url, data, config)
   .then(response => {
    resolve();
   }, err => {
    reject();
   })
 })
}

/**
  * patch method encapsulation
  * @param url
  * @param data
  * @returns {Promise}
  */
export function patch(url, data = {}, config = {
 "headers": {
  'Content-Type': 'application/json', //Set cross-domain header  "Authorization": 'JWT ' + ("authToken")
 }
}) {
 return new Promise((resolve, reject) => {
  (url, data, config)
   .then(response => {
    resolve();
   }, err => {
    reject();
   })
 })
}

/**
  * put method encapsulation
  * @param url
  * @param data
  * @returns {Promise}
  */
export function put(url, data = {}, config = {
 "headers": {
  'Content-Type': 'application/json', //Set cross-domain header  "Authorization": 'JWT ' + ("authToken")
 }
}) {
 return new Promise((resolve, reject) => {
  (url, data, config)
   .then(response => {
    resolve();
   }, err => {
    reject();
   })
 })
}

(This is the program entry file in the src directory)

<template>
 <div >
 <router-view/>
 </div>
</template>

<script>
import axios from 'axios';
let protocol = ; //protocollet host = ; //Hostlet reg = /^localhost+/;
if((host)) {
 //If the local project is debugged and used  = 'http://10.:xxxx/api/';
} else {
 //Dynamic request address  = protocol + "//" + host + "/api/";
}
 = 30000;
export default {
 name: 'app',
 axios //Remember to export here. If the request address is permanently fixed, then configure a baserURL according to the `Normal Version`}
</script>

<style lang="scss"> //I'm using scss here@import '~@/style/style'
</style>

Summarize

Frequently Asked Questions

When using the dynamic version, why is it called dynamic? It is because the access address and the request address are the same address and the port number. For example, if I access the project through (default port 80), then my baseURL will automatically change to http::80/api/. The reason for this is that when the project is migrated or http is changed to https one day, you don’t need to change the request address again, the program will be completed automatically.
Is the data request address configured incorrectly? If you configure baseURL, then the encapsulated function only needs to pass in the request address based on the baseURL when using it. For example, if you pass in login/, the request address will automatically become http::80/api/login/. If not configured, you can directly pass in the entire request address.

Things to note

When using the dynamic version, since there is no interceptor, the function encapsulated below needs to be written when returning an error.to get the returned data, but I wrote it, because this way you can get the status code and other information. If you do not need to judge the returned status code, it will be changed toJust do

Okay, the above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.