Basic use of axios

Features:

1. Promise-based asynchronous ajax request library

2. Both browser and node can be used

3. Support request and response interceptor

4. Support Request Cancellation

5. Request and response data conversion

6. Send multiple requests in batches

use:

Default get request: axios({url: ""}).then(res=> {console.log(res), err=>{console.log(err)}}) or axios.get("/get", {}).then()

post request: axios({url: "", method: "post"}).then() or axios.post("/post", {}).then()

put请求:axios({url: "", method: "put"}).then()或者axios.put("/put", {}).then()

delete请求:axios({ur: "", method: "delete"}).then()或者axios.delete("/delete", {}).then()

Axios.get() request and axios.delete() request, receive two parameters, URL and config configuration object

Axios.post() request and axios.put() request receive three parameters, URL, request body and config configuration object

The corresponding result analysis for the request:

insert image description here

Commonly used configuration items for configuration objects:

URL: "/user" path URL

method: "get" request method: default get

basURL: "http:localhost:8080/" base URL, the final URL of the request is spliced ​​together by baseURL+URL, setting the default globally can make the URL of the sending request concise

headers: { "X-Requested-With": "XMLHttpRequest" } Set the request header

params: { id: 12345, name: 'jack' } Set the query parameters of the request URL

data: { firstName: 'fred' } The setting request body can also be directly set as a string data: "firstName=fred"

timeout: 1000 request timeout, in milliseconds, default 0, no timeout

responseType: "json" sets the response data type, the default is json

responseEncoding: "utf8" The encoding format of the response data, the default is uuf-8

maxContentLength: 2000 The maximum length of the response body

maxBodyLength: 2000 The maximum length of the request body

validateStatus: function (status) { return status >=200 && status < 300 } When setting the response status code, it is successful, call resolve, otherwise call reject fails, the default is greater than or equal to 200, less than 300

You can use the format of axios.defaults.baseURL="" to set the global default configuration, in order to avoid multiple repeated configurations repeated in different requests

axios.create()

axios.create(config) repackages the axios request

1. Create a new axios according to the specified configuration, that is, each axios has its own configuration

2. The new axios just does not have the method of canceling requests and batch requests, and all other syntaxes are consistent

3. Why this syntax?

​ 1) Requirements, the configuration required by some interfaces in the project is different from the configuration of other interfaces

​ 2) Solution: Create two axios, each with its own configuration, corresponding to different requirements in the interface request

Simple use: (request multiple port numbers at the same time)

const instance = axios.create({ baseURL: "http://localhost:3000" })

const instance2 = axios.create({ baseURL: "http://localhost:4000" })

instance({url: '/get'})

instance2({url: '/get'})

Axios interceptor:

1. Request interceptor: It is used to intercept requests, customize a logic and then send the request. It can be used to configure common logic, so there is no need to configure every request

use:

// Add a request interceptor to pass in two callbacks, the first successful callback and the second failed callback

      axios.interceptors.request.use(

        (config) => {

          // config configuration can be used to display a synchronous animation on the page when sending network requests

          // Some requests (such as login (token)) must carry some special information

          // The request was successfully intercepted

          console.log("request interceptor");

          return config;

        },

        (err) => {

          // Request failure interception

          return Promise.reject(err);

        }

      );

2. Response interceptor: used to intercept the response, do some processing and then send the response callback

use:

// Add a response interceptor Pass in two callbacks, the first is a success callback, and the second is a failure callback

      axios.interceptors.response.use(

        (res) => {

          // res response result

          // Response successfully intercepted

          console.log("Response Interceptor");

          return res;

        },

        (err) => {

          // Response failure interception

          return Promise.reject(err);

        }

      );

After adding multiple interceptors, the request interceptor is similar to a stack, last in first out, the one added first is executed later, and the one added later is executed first, the response interceptor is similar to a queue, first in first out, and the execution order is in the order of addition.

cancel request

The cancellation request means that after sending the request, if there is no response for a period of time, you can cancel it.

When axios sends a request, adding the cancelToken configuration item can be used to cancel the request. There are two ways to get the value of cancelToken:

1. Axios has a CancelToken attribute, which is a class that can be used to obtain the cancel method of the cancellation request. After obtaining this method, cancel() can be executed in an appropriate place to cancel the request, which can be used to cancel multiple requests

use:

       const CancelToken = axios.CancelToken;

      let cancel;

      axios.get("/get", {

        cancelToken: new CancelToken(function (c) {

          cancel = c;

        }),

      });

      cancel();

2.CancelToken has a source static method, which returns an object after calling, which contains a token attribute for marking the request and a cancel method for canceling the request

use:

       const CancelToken = axios.CancelToken;

      const source = CancelToken.source();

      axios.get("/ge", { cancelToken: source.token });

      source.cancel();

Basic process: 1. Configure the cancelToken object, 2. Cache the cancel function used to cancel the request, 3. Call the cancel function to cancel the request at a specific time later, 4. Judging in the error callback, if err is cancel, do the corresponding processing.

Use 1:

       // Step 1: define a cancel global variable, the initial value is null

      let cancel = null;

      axios

        .get("/get/", {

          // Step 2: In the requested configuration object, configure the cancelToken attribute value, and assign the c parameter of the function to the global variable cancel

          cancelToken: new axios.CancelToken((c) => {

            cancel = c;

          }),

        })

        .then((res) => {

          console.log(res);

        })

        .catch((err) => {

          console.log(err);

        });

      // Step 3: Calling the cancel function is to cancel the request reception

      cancel();

Use 2: Unify the cancellation request in the request interceptor

        axios.interceptors.request.use(

        (res) => {

          res["cancelToken"] = new axios.CancelToken(function (c) {

            cancel = c

          });

          return res;

        },

        (err) => {

          return Promise.reject(err);

        }

      );

Use 3: Unify the cancellation request in the response interceptor

axios.interceptors.response.use(

        (res) => {

          return res;

        },

        (err) => {

          // Break the promise chain if the error is caused by a cancel request

          if (axios.isCancel(err)) {

            // break the promise link

            return new Promise(() => {});

          } else {

            // Pass the error down

            return Promise.reject(err);

          }

        }

      );

      // The previous interface has not responded yet, the next interface starts to request, and the previous interface is canceled

      let cancel;

      axios.interceptors.request.use(

        (config) => {

          if (typeof cancel === "function") {

            cancel("The request was forcibly canceled");

          }

          config["cancelToken"] = new axios.CancelToken(function (c) {

            cancel = c;

          });

          return config;

        },

        (err) => {

          return Promise.reject(err);

        }

      );

      axios.interceptors.response.use(

        (res) => {

          cancel = null;

          return res;

        },

        (err) => {

          cancel = null;

          if (axios.isCancel(err)) {

            console.log("Cancel previous request");

            // Break the Promise link

            return new Promise(() => {});

          } else {

            // Pass the error down

            return Promise.reject(err);

          }

        }

      );

Guess you like

Origin blog.csdn.net/m0_46318298/article/details/128372946