Network module selection

  • Option one, native Ajax. Configuration and invocation are very confusing. There are few options in development, instead using Ajax wrapped in jquery.
  • Option 2, Jquery-wrapped Ajax. Rarely used when developing vUE projects. Because we didn’t rely on jquery to develop the Vue project. So in order to use Ajax wrapped in jquery.
  • Option three, the Axios framework. And that’s our final choice. It has many advantages such as support for Promises, and support for intercepting requests and responses.

Use the AXIos framework

Install the AXIOS framework

npm install axios --save
Copy the code

Import the AXIOS framework

import axios from "axios"
Copy the code

Axios makes simple use of network requests

You can just use Axios.

  • Axios (config) Config is configuration, that is, some configuration for the network request.
  • Axios.get (url,[config]) uses this method with the first argument being the URL
  • axios.post(url,[data,[config]])

. In fact, they may be a little different in form, but in essence they are almost the same.

axios(config)

The default request for axios(config) is a GET request, and of course you can configure its method property through config to specify how it is requested.

Axios ({url: "http://123.207.32.32:8000/home/multidata"})Copy the code

This is a basic request. (The default is GET.) In Ajax, after the request succeeds, the function in SUCCESS is called to process the requested data. So how do we do that in Axios? Axios () itself returns a Promise object, and when the request succeeds, the resolve() function is called by default, so you can execute the code that requested the successful processing of data in the then method. Similarly, when a request fails, the reject function is called by default. The catch method is then called by default

Axios ({url: "http://123.207.32.32:8000/home/multidata"}). Then (res = > console. The log (res)). The catch (err = > console. The log (err))Copy the code

Like my form is the most basic use. Let’s print the RES.It’s this object. In essence, the server gives the data attribute, which means that obj. Data is the data that the server sends. It is the AXIos framework that has taken it upon itself to wrap so many other attributes around the incoming data.

Axios’ GET request passes parameters

How do I pass parameters when I make a GET request?

  • Method one is to concatenate data directly in the URL.

The parameters of our GET request can be concatenated directly after the URL. Such as:

Axios ({url: "http://123.207.32.32:8000/home/multidata? aaa=1&type=2" }).then(res=>console.log(res))Copy the code

Simply concatenate the data on the URL.

  • Method 2: Configure the params attribute in config
Axios ({url: "http://123.207.32.32:8000/home/multidata", params: {aaa: 1, type:2 } }).then(res=>console.log(res)).catch(err=>console.log(err))Copy the code

Axios sends concurrent requests

Some services require both network requests to be successful before proceeding to the next operation. At this point, we can use Axios to send through:

axios.all([]); // Pass in an array whose elements are an AXIos network requestCopy the code
Axios. All ([axios ({url: "http://123.207.32.32:8000/home/data"}), Axios ({url: "http://123.207.32.32:8000/home/multidata"})]), then (res = > console. The log (res))Copy the code

And then we’re going to do it all in the THEN method, and notice that the RES in the THEN method is an array and it should be an array of two requests that have been requested.

Axios configuration is related

The basics of config

What can be configured in config?

  • So baseURL, baseURL is the common part of the URL so let’s pull them out, so that’s baseURL. He’ll concatenate it with our URL. For example, the two urls above, we can puthttp://123.207.32.32:8000Assign to baseURL, so our URL is not that long
Axios ({baseURL: "http://123.207.32.32:8000", url: "/ home/data"})Copy the code
  • Url request path
  • Method Indicates the request type
  • Params get Request parameter transfer
  • Timeout Timeout setting
  • Data POST Requests parameters to be transmitted

The default value of config

We can see that many requests and many configuration items are the same. Then we can set the default value of the configuration item

Set mode

axios.defaults.baseURL[=""
Copy the code

It looks like this.

Pay attention to the point

Here we’re using Axios directly. That’s a global AXIos. In fact, AXIos can create many instances, and the default values above are only for configuring network requests using global AXIOS.

An example of axios

Why create an instance of Axios

Because if you’re using global AXIOS, then you only have one set of default configurations, and maybe A lot of requests have baseURL OF A and A lot of requests have baseURL of B. Then a default configuration is cumbersome. At this point we can create multiple instances. There are many sets of default configurations.

How do I create an instance of Axios

let instance1 = axios.create({
baseURL:"",
timeout:5000
})
Copy the code

The object passed in by the create method is the default configuration for this instance.

Axios encapsulation

Why encapsulate Axios

If many of our components are going to make network requests, we need to import the AXIos framework into their.vue files.

import axios from "axios"
Copy the code

This led to a serious problem that our project relied too heavily on this third-party framework. Just in case the framework is buggy or not updated, we have to replace the framework, it is very troublesome. So the best thing we can do is encapsulate our own third-party framework and use our own to do network requests in the project. In this way, even if we change the third party framework we only need to do the packaging in the JS code to deal with it.

Simply encapsulate Axios

Create a new.js file request.js:

import axios from "axios"
export function instance1 (config,success,failure){
  let instance = axios.create({});
  instance(config).then(res=>success(res)).catch(err=>failure(err))
}
Copy the code

In the component to make the network request:By wrapping we just export this function that I’ve wrapped. And this function takes three arguments

  • The first parameter, the object, is the configuration associated with the network request.
  • The second argument, the function, is the operation to process the data if the network request succeeds
  • The third argument, the function, is the action to take if the network request fails

There’s another option: in request.js:

import axios from "axios"
// export function instance1 (config,success,failure){
//   let instance = axios.create({});
//   instance(config).then(res=>success(res)).catch(err=>failure(err))
// }
export function instance1 (config){
  let instance = axios.create({});
  return  instance(config);
}

Copy the code

Among components that use network requests:What does that mean? The basic idea is that instead of passing in the successful operations and the failed operations, I’m just going to send the network request back. I mentioned earlier that the network request actually returns a Promise object, so I’m just going to return the network request, and you’re going to write the data and the operations that you’re going to do in the component, so don’t pass it in.

Axios interceptor

As mentioned earlier, AXIos can intercept requests and responses. He offers a counterpoint:

Intercept request

Interception method:

axios/(axios.instance).interceptors.request.use(config=>{return config},err=>{})
Copy the code
  • If the request is successfully intercepted, it executes config=>{}, which intercepts the configuration of the request (we just configured a lot of things for the request), and assigns the value to config.



config:

  • If a request fails to be intercepted, err=>{} will be executed.

Pay attention to the point

If you block the configuration of others, you must return it, otherwise others will not be configured!! So be sure to return config.

Intercept the response

axios/(axios.instance).interceptors.response.use(res=>{return res; },err=>{})Copy the code
  • When the response is successfully intercepted, res=>{} is executed, which intercepts the requested data (wrapped in AXIos, of course) and assigns the value to res.
  • If the interception response fails, err=>{} is executed.

Pay attention to the point

Response interception success must also return data, otherwise the page was intended to render data truncated by your page will not render out.