1, the introduction of

In vue.js you can complete Ajax requests using Axios, a Promise-based HTTP library

The text of this article is not much, it is mostly code, and the explanation is also written in the comments

Interested friends can also go to the official document: www.axios-js.com/zh-cn/docs/

2, installation,

(1) the CDN

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code

(2) the NPM

> npm install axios
Copy the code

3, GET request

<! DOCTYPE html><html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.js"></script>
</head>

<body>
    <div id="app">
        <p>{{ info }}</p>
    </div>

    <script>
        new Vue({
            el: '#app'.data: {
                info: null
            },
            mounted: function () {
                let _this = this;
                // GET: axios.get(url[, config])
                // You can add parameters to the URL
                axios
                    .get('http://www.httpbin.org/get?firstName=Steve&lastName=Jobs') 
                    .then(function (response) { _this.info = response.data; })
                    .catch(function (error) { console.log(error); }); }})</script>
</body>

</html>
Copy the code

4. Response structure

When we send a request, what is the response that we receive? Let’s take a look

{
    // The data returned by the server
	// http://www.httpbin.org is a site used to test the request, and the data it returns is the requested information
    data: {},

    / / status code
    status: 200.// The status information corresponding to the status code
    statusText: "OK"./ / response headers
    headers: {},

    // Provide configuration information for the request
    config: {}}Copy the code

5. POST requests

<! DOCTYPE html><html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.js"></script>
</head>

<body>
    <div id="app">
        <p>{{ info }}</p>
    </div>

    <script>
        new Vue({
            el: '#app'.data: {
                info: null
            },
            mounted: function () {
                let _this = this;
                // axios.post(url[, data[, config]])
                // Parameters can be added using data
                axios
                    .post('http://www.httpbin.org/post', {
                        firstName: 'Steve'.lastName: 'Jobs'
                    })
                    .then(function (response) { _this.info = response.data; })
                    .catch(function (error) { console.log(error); }); }})</script>
</body>

</html>
Copy the code

5. Request configuration

In addition to the two common uses above, we can also pass the axios() method a configuration object that contains the relevant configuration for the request

For example, we could send a simple GET request this way:

axios({
    url: 'http://www.httpbin.org/get'.method: 'get'.params: {
        firstName: 'Steve'.lastName: 'Jobs'}})Copy the code

Similarly, we can send a simple POST request in this way:

axios({
    url: 'http://www.httpbin.org/post'.method: 'post'.data: {
        firstName: 'Steve'.lastName: 'Jobs'}})Copy the code

In addition, some common configuration items are as follows:

  • url: Request URL, the only required field
  • baseURL: Automatically added inurlBefore, so thaturlUsing relative paths
  • method: Request method, default is GET
  • headers: request header
  • params: Request parameters
  • paramsSerializerWill:paramsserialization
  • data: Request data
  • transformRequest: Allows request data to be modified before sending the request
  • transformResponse: Allows the response data to be modified before receiving the response
  • timeout: Specifies the timeout period
  • withCredentials: indicates whether credentials are required for cross-domain requests. The default value is false
  • auth: indicates that HTTP basic authentication is used and credentials are provided
  • responseType: Data type of the server response. The default value is JSON
  • maxContentLength: Indicates the maximum length of the server response

We can also set the default value for the request configuration:

// For example, set baseURL to https://www.example.com
axios.defaults.baseURL = 'https://www.example.com'
Copy the code

6. Interceptors

We intercept requests or responses before then() or catch() and do some processing on them

// Add request interceptor
var RequestInterceptor = axios.interceptors.request.use(function (config) {
	// What to do with the requested data
	return config;
}, function (error) {
	// Do something about the request error
	return Promise.reject(error);
});

// Add a response interceptor
var ResponseInterceptor = axios.interceptors.response.use(function (response) {
	// What to do with the response data
	return response;
}, function (error) {
	// Do something about the response error
	return Promise.reject(error);
});
Copy the code

If you want to remove interceptors, it’s easy

// Remove request interceptor
axios.interceptors.request.eject(RequestInterceptor);

// Remove the response interceptor
axios.interceptors.response.eject(ResponseInterceptor);
Copy the code

7. Concurrent requests

Axios.all () can batch requests and wait for all requests to return a result before performing a callback

axios.all([
    asyncMethodOne(),
    asyncMethodTwo()
])
.then(axios.spread(function (resOne, resTwo) {
    AsyncMethodOne and asyncMethodTwo are now complete
    // resOne and resTwo are responses returned by two requests, respectively
}))
Copy the code

Supplement: RECENTLY, I encountered a cross-domain problem when writing AXIos. It took me a long time to check the data before I finally solved it. I will also write it down for record here

The problem is that I’m using axios to request a third party weather query in a project I’m building with @vue/ CLI

T.weather.sojson.com/api/weather… (GET request, open browser can see the return result directly)

Then, following the pattern above, it is easy to write the following code:

axios
    .get('http://t.weather.sojson.com/api/weather/city/101280101')
    .then(function(res) { console.log(res); })
    .catch(function(err) { console.log(err); })
Copy the code

However, when we run the project NPM run serve and open the browser console to check the result, error message is as follows:

Access to the XMLHttpRequest at ‘t.weather.sojson.com/api/weather…

From origin ‘http://localhost:8080’ has been blocked by CORS policy:

No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Later I checked on the Internet and found that due to the same origin policy, we could not directly make cross-domain requests

The so-called cross-domain request refers to the request URL and the current page URL protocol, domain name, port three any different

So what’s the solution? The following is the solution of using axiOS for cross-domain request in the development environment of the project built with @vue/ CLI

  1. Create a new one in the root directory of the projectvue.config.jsConfiguration file, and add configuration code to the file
// vue.config.js
module.exports = {
    // Use the back-end API server to send requests, which can avoid cross-domain problems
    devServer: {
        proxy: {
            // Custom identifier, proxy only used when request begins with '/sojson'
            '/sojson': {
                // The protocol and domain name of the target host
                target: 'http://t.weather.sojson.com'.ws: true.changeOrigin: true.// Path rewrite to replace '^/sojson' with '' when sending a request
                pathRewrite: {
                    '^/sojson': ' '
                }
            }
        }
    }
}
Copy the code
  1. useaxiosSend the request, notice the change in the request address
axios
    .get('/sojson/api/weather/city/101280101')
    .then(function(res) { console.log(res); })
    .catch(function(err) { console.log(err); })

/ / at this point, the requested URL '/ sojson/API/weather/city / 101280101'
// Since the request begins with '/sojson', which conforms to the custom identifier, the proxy is used
// Since the request begins with '/sojson', which conforms to the path rewriting rule, replace it with ''
/ / stitching on the target host protocol and domain name 'http://t.weather.sojson.com'
/ / in the end use the proxy to send request for 'http://t.weather.sojson.com/api/weather/city/101280101'
Copy the code
  1. Finally, restart the projectnpm run serve(important), you can implement cross-domain requests

I recently ran into a problem where THE GET request didn’t work, but the POST request didn’t GET the correct data

For example, we use a POST request youdao translation interface: fanyi.youdao.com/translate

As above, we need to solve the cross-domain problem first, just write the configuration in the vue.config.js file

module.exports = {
    devServer: {
        proxy: {
            '/youdao': {
                target: 'https://fanyi.youdao.com'.ws: true.changeOrigin: true.pathRewrite: {
                    '^/youdao': ' '
                }
            }
        }
    }
}
Copy the code

Then, use Axios in a similar way as above

axios({
    url: '/youdao/translate'.method: 'POST'.data: {
          'i': 'Hello'.// Translation content
          'doctype': 'json'.'from': 'AUTO'.'to': 'AUTO'
    }
}).then(function(res) {
    console.log(res);
}).catch(function(err) {
    console.log(err);
})
Copy the code

But when you run the project, you realize that we don’t have the right data, so we just need to make a little change

import qs from 'qs'
let fromData = {
    'i': 'Hello'.'doctype': 'json'.'from': 'AUTO'.'to': 'AUTO'
}
axios({
    url: '/youdao/translate'.method: 'POST'.// Set the request header content-type
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    // Serialize the object as a URL
    data: qs.stringify(fromData)
}).then(function(res) {
    console.log(res);
}).catch(function(err) {
    console.log(err);
})
Copy the code