Learn Axios from the shallow to the deep

In 2021, how can anyone not be allowed to aiOXs? I will share some of my own experiences with Axios. It gives you a quick introduction to Axios.

Basic introduction

Axios is a network request library that is widely used at the front end, including Vue. The author also recommends using Axios in Vue.

  • The main features include:
    • Send it in the browserXMLHttpRequestsRequests;
    • innode.jsSent inhttpRequests;
    • supportPromise API;
    • Intercepting requests and responses;
    • Transform request and response data;
    • And so on;

Project Environment Introduction

Create a vUe-only project using the @vue/ CLI 4.5.13 version, and install the NPM install AXIOS library after creation

So the environment of the whole project looks like this

Of course, this is not to say that AXIos can’t be used in non-VUE environments, I’m just doing this for code convenience. Normally, using the browser script tag to introduce AXIos, there will be an Axios object on the window object, So you can use it in the browser environment exactly the same as I used it in vUE.

It looks something like this:

  • The introduction of

  • The effect

Request the address

httpbin.org/

I think you’ve all heard when you’re learning about HTTP at this site, that if you make a request to this site, the content that you send in the request will come back as it was.

The basic use

First request

Let’s start by looking at the list of AXIos apis that the official documentation gives us

axios(config) axios(url[, Config]) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- line -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- axios. Request (config) axios. Get ([url, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])Copy the code

The method in front of the split line is officially given as an example, and the method behind the split line is officially only mentioned.

I might be a little confused here, but if I write some code, I can see it immediately.

According to axios’ official documentation. Let’s start with a simple get method.

In app.vue, we introduce Axios and use Axios to send a GET request with parameters.

Let’s start by looking at the browser’s web requests

As you can see, the request we made was successful. Let’s now look at the printed response from our THEN.

We found that there seemed to be more printed out in then than in the return value of our network request. But the corresponding value of data is the result of our request.

Ok. By now, we can use Axios to send network requests. But we still have a lot of questions.

  1. axios({})This method makes a network request, but what does the object passed by the method mean?
  2. thenprintoutresWhy are there so many other arguments in the return value?

Axios configuration

Axios has a lot of documentation for this. Of course, if you’re new, it might look really bad. Ah, I’m just going to learn axios. Is there that much to remember?

Of course not! I will now briefly use my understanding to translate some common configurations

{
  // Url (common) indicates the address we use to send the request
  url: '/user'.// method indicates the method we use to send requests. The default is get
  method: 'get'.// baseURL(common) means that we send the request and the URL, the final address of the request is baseURL+ URL
  baseURL: 'https://some-domain.com/api/'.// Headers (common) Configures the request header of the network request that we send, usually carrying a token for authentication
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // Params is used to concatenate objects as parameters to the URL. username=xiaomin&password=123456
  // Usually where get requests take parameters (important)
  params: { username: 'xiaomin'.password: '123456' },

  // Data (common) Parameters in data are placed in the request body
  // Usually post, PUT,delete where the request takes parameters (important)
  // Binary can be transferred. For example, FormData objects for uploading images can be transferred with data
  data: {
    firstName: 'Fred'
  },

  // timeout(common) Specifies the timeout period for a request. If the request does not respond after the timeout period, a catch message will be sent. The default value is 0, indicating that the request is waiting for a response
  timeout: 1000.// onUploadProgress is used to monitor the progress of upload
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event}},Copy the code

These are common configurations and I recommend keeping them all in mind, but I’ll use them later to do some more advanced axios uses

Returns an introduction to the wrapped object

By default, axios wraps our request when it returns the value.

The official documentation page gives a very detailed explanation, I will use my language to translate.

{
  // Request the return value of the response
  data: {},
  // Request status
  status: 200.// Status description text
  statusText: 'OK'.// The request header of the request
  headers: {},
  // The configuration used in this request refers to the configuration in question 1
  config: {},
  // The request instance represents information about the XMLHttpRequest wrapped under AXIOS
  request: {}}Copy the code

Ok. Now we have an idea of the process from the initiation of the request to the result of the response.

Here are some things that are often overlooked and some tips

A small misunderstanding

We see the code above, because we made the request,

  1. The parameters of a GET request are usually concatenated to the URL, so we use the params configuration in AXIos to carry our request parameters
  2. The parameters of a POST request are normally placed in the request body, so we use the data configuration in AXIos to represent our request parameters

tip

In the axios API introduction,

For GET, we found that there is also such an API. axios.get(url[, config])

So let’s try to play with it, modify our testGet method, okay

As you can see, the AXIos. get API just strips out the URL and method configurations.

Notice that axios.get takes two arguments, the first is the URL and the second is our configuration option.

Pay attention to

So the question is, what’s the difference between the two?

Look at the source code for definitions.

Index.js in the axios package introduces./lib/axios, and here we have./core/ axios

In this./core/Axios. We can see the following.

As you can see, he is binding the stereotype to get post put…. MergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig mergeConfig

In line 29 we also define the request method, which is basically optimized for configuration

Such as method name case conversion.

For example, it eventually returns a promise object wrapped around us

So essentially, axios({}) and our axios.get(url,{}) are two identical methods.

Ok, axios. Post axios. Put, etc., similar to get

These two methods can be said to be radish cabbage, each has his favorite. Everyone has their own preferences, so it’s up to you which method you use.

File upload

So without further ado,

uploadImg() {
  console.log(this.file);
  const formData = new FormData();
  formData.append('file'.this.file);
  axios({
    url: 'XXXXXXXXXXXXXXXXXXXXXXXXXX'.method: 'post'.data: formData,
    onUploadProgress(progressEvent) {
      let complete = (((progressEvent.loaded / progressEvent.total) * 100) | 0) + The '%';
      console.log('upload' + complete);
    },
  }).then((res) = > {
    console.log('uploadImg res==>', res);
  });
},
Copy the code

Where this.file is the value of e.target.files after our input type is file. Of course, this value is array, we need its first one

Notice that data is passed as an argument of type FromData.


Ok, here, we will simply learn the use of axios, of course, there will be a lot of friends say that ah, this thing is not at a glance can be?

Now that you see this. I’m not gonna let you do this for nothing. Let’s add it up and talk about advanced usage.

Advanced usage

Before we look at advanced usage, we need to ask why we do this. What were the problems with what we did?

  1. In our real development environment, we would wire the address, develop the address, test the address. How can we switch these addresses quickly?
  2. What we found was thataxiosOne of the things that we change every timeurl method data paramsWhat has rarely changed is thatheader baseurl timeout, so can we uniformly encapsulate those that rarely change?
  3. Each time I want to send a request in the console output my current request information, can encapsulate, do not write every time.
  4. axiosThere are too many things we don’t need in the return value ofdataEvery time a request comes backres.dataNow, this is boring. Can we skip this step?
  5. Requests tend to encounter errors that I need to make every timecatchThe code is smelly and long, but it is clearly only onelog errorFunction, but every time the request place need to writecatchCan you omit it here?

Ok, now that we have a problem, it’s going to be a lot easier to write code. One by one, we’re done.

Axios object

First, we introduce AXIos, which uses axios({}) directly to make a network request. There are three ways to configure a network request in AXIos

Global Default Configuration

We can do the default configuration directly on axios.default

// Global default configuration
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 1000 * 5
Copy the code

Axios instance configuration

Axios has a create method that returns an AXIos object, but we can specify some default configurations in create that will be used by the returned instance object.

// The axios instance is configured by default
const request = axios.create({
  baseURL: 'https://api.example.com'.timeout: 1000 * 8
});
Copy the code

Axios method configuration

We’ve seen this before, so I won’t go into it.

// Method configuration
axios({url: ' '.baseURL: 'https://api.example.com'.timeout: 1000 * 10})
Copy the code

Ok, three configurations were introduced. Let’s talk about the priority of the configuration

  • Priority isrequesttheconfigParameter configuration;
  • The second is the casedefaultConfiguration in;
  • Finally, the global configuration;

Production environment, development environment, test environment.

Many of you may not understand the difference between these three environments.

First, assume that our three environments correspond to the following addresses

// Production environment
192.168. 01.:8080/
// Development environment
192.168. 01.:8080/dev/
// Test the environment
192.168. 01.:8080/test-a/
Copy the code

Separation of the first, before and after the project is the end, we will be writing the code in the test environment, test environment mean, front-end and back-end code is written in real-time, such as front-end docking backend we have 2 people A, B, the development environment is A function of the request is to be sent to A computer after (A) in the development, The address may be 192.168.0.1:8080/ test-A, and the code will be written tomorrow to connect with B again. At this time, the request will be sent to B’s computer, and the address may be 192.168.0.1:8080/ test-B. The test environment means that the code is being written in real time, and the functional structure is being tuned locally to someone else.

Now that the code has been in development for a week and is ready, it will be submitted to the development environment. In this case, the interface is connected to the 192.168.0.1:8080/dev address

First of all, we always write code in the test environment, submitting to the development environment is a small version of the code, and the code in the development environment does not change as fast as our local test environment, and we later write other functions in the test environment.

Committed to the development environment, the inside of the products of the company, the tester, will be on the development environment, use your code, look at your code for any bugs, if there is a bug, you need to modify a bug in your test environment, the modification is completed in the committed to the development environment to test, until finally no bug, The code from the development environment is then submitted to production, which means that the code is intended for use by users who don’t know anything.

It’s a little convoluted, just to summarize.

Production environments are user-oriented

The development environment is for testers, they come to find bugs

The test environment is for us coders, where we write code

, of course, there are a few small company is no test environment, each time the code is the backend written submission to the development environment, the front-end direct docking of a development environment, a problem the backend to change the code, change after the need to pack into the development environment, so that the front can continue, there is no test environment directly connected to the back end on the development of the computer is so convenient.

baseUrl

What is this baseUrl? People who see it for the first time may be a little confused. Here’s an example:

The interface for adding user functionality might look like this:

// Production environment
192.168. 01.:8080/user/add
// Development environment
192.168. 01.:8080/dev/user/add
// Test the environment
192.168. 01.:8080/test-a/user/add
Copy the code

When we add a user, we only care about the path /user/add. Even if we change the path behind the environment, we will not change the path.

Sure, that’s what baseUrl does

The actual request address = baseUrl + URL


Ok, so with that in mind, let’s start wrapping our Axios

Encapsulate the axiOS default configuration

Let’s change our file directory structure first.

There is a request.js in utils, where we wrap our Axios.

In the API directory we have user.js where we use our encapsulated request to manage user-related interfaces

Where we need to tune the interface, we just import the methods in the API.

Start by writing the following code in utils/request.js.

Write some code in API /user.js

Call in the app. Vue

Ok, so that depends on us to solve questions 1 and 2 that we raised earlier

Request interceptor

The official documentation tells us that the axios instance has a request blocker, which does some interception of our request.

Let’s write some code to see what this config is

Print the result

So it’s our Congif, so let’s customize it

So we’re done with problem number three

Add a Token request header

In the request, we often add the token field for authentication. There are many methods to add the token. Here I will introduce several common ones, only responsible for adding. Whether or not the addition succeeds, the back end will report an error if it fails, and then we’ll deal with the back end reporting an error.

  1. API manual add, I need to add, the code is as follows

  1. Add a custom parameter to the requesttokenWhether the field is required.

This field is then judged for processing in our request interceptor

The response way

Before we solve problems 4 and 5. Let me summarize some of the responses I’ve encountered.

Method 1: the back end does not solve the error, directly throw to the front end, here we can feel the most intuitive is the return status code is 500.

Method 2: the back-end solution error report, each time the error package back to the front end, here we feel the most intuitive is. It’s not going to be a 500 error request every time it’s going to be a 200 success request, but it’s going to return a little bit more, so for example, the return value, of course, the following code, MSG, different companies have different specifications.

{
    // The return value of our actual request
  	data: {... },// We actually request the status code, the backend packaging error flowers, this code will change, such as 500, or each company has a direct status code specification
    code:200.// The server gave us the information, generally successful without information, there is an exception this field indicates the error cause
    msg:"Request successful"
}
Copy the code

Response interceptor

Let’s take a look at the official documentation and see how we can write our code and print out this response.

Because the address for the interface written according to user is fake, I’ll switch to httpbin.org/get to show the effect, but the logic here…

We found that the response interceptor would just pass over our results so that we could do some coding here.

For example, problem 4, we just need to write it like this.

Now let’s deal with our toughest problem. How to intercept errors?

Let’s start with elementUI (NPM I element-UI-s), where we use the Message component to pop up when we encounter an error.

Before intercepting errors, we need to understand our own set of response policies, which we treat differently.

First let’s deal with the request error, say 404,500, etc

Import {Message} from ‘element-ui’ in the first line;

This error still needs to return, so that it can be caught by our own catch. We just encapsulate the global error message here, and sometimes we need to handle our own catch for some requests.

If the request is normal, we still have to deal with it, because sometimes the company backend will intercept the error itself and return the status code 200, but this time the data is not correct and there is an error message

Here we specify that all requests will have data,code, MSG fields. The code is 200 if the request succeeds, and data returns normal data. If the request fails,code is an error status code. (Write according to the background interface specification of your own company when encapsulation)

Ok The complete code is as follows, the first imported Router

Details of the optimization

At this point our axios encapsulation is complete, but there is still a little bit of direction to optimize

  1. For example, some people like it.get() .postSend a request, now written as a configuration is hard to write
  2. getPass byparams.postPass bydataNeed to remember, very troublesome, we all encapsulate, can you make him more powerful.

According to the above two requirements, we will continue to modify.

I’m going to change the export method, wrap the higher-order functions, and we’ll do it ourselves

The end result is as follows

conclusion

Summarized in the process of using axios my experience, I here page introduces the concept of the less than many of the new contact, such as test/development/production environment is stem what of, have what distinction, for example, HTTP request response way now this according to the different companies have different ways, if you don’t know the backend or no development experience, This could still be foggy.

Of course, I also dish chicken, if the article help to sprout new, my purpose is achieved, if the big guy saw that the whole article is nonsense, then when review it

I’ll upload the code to Gitee, download it yourself if you need to.

The source address