With vuejs The author, you Yuxi, released the news , No longer maintained vue-resource, And recommend that you use axios Start ,axios Be known by more and more people . Originally, I wanted to find a detailed strategy on the Internet , Suddenly found that ,axios The official document itself is very detailed !! What else do you want with this bike !! So I recommend you to learn this library , It's best to read its official documents in detail . I have translated it axios Official documents of , I believe that as long as you have a thorough understanding of this article, you can put it into practice ,axios It's just a small thing !!

If you find this article helpful , You might as well like it or pay attention to it , Your encouragement is very important to me .

axios brief introduction

axios It's based on Promise For browsers and nodejs Of HTTP client , It has the following characteristics :


  • Created from the browser XMLHttpRequest
  • from node.js issue http request
  • Support Promise API
  • Intercept requests and responses
  • Transform the request and response data
  • Cancel the request
  • Automatic conversion JSON data
  • Client support prevents  CSRF/XSRF

Browser compatibility

Introduction mode :

1
2
3
4
5
$ npm install axios
$ cnpm install axios //taobao Source
$ bower install axios
Or use cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Take a chestnut :


perform GET request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// To have specified ID The user who made the request
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
 
// It can also be done through params Object passing parameters
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

perform POST request

1
2
3
4
5
6
7
8
9
10
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Execute multiple concurrent requests

1
2
3
4
5
6
7
8
9
10
11
12
function getUserAccount() {
return axios.get('/user/12345');
}
 
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
 
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Two requests are now complete
}));

axios API


This can be done by passing the relevant configuration to axios To make a request .

axios(config)

1
2
3
4
5
6
7
8
9
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});

axios(url[, config])

1
2
// Send a GET request (GET Request is the default request mode )
axios('/user/12345');

Request method alias

For convenience , Aliases have been provided for all supported request methods .

  • axios.request(config)
  • axios.get(url [,config])
  • axios.delete(url [,config])
  • axios.head(url [,config])
  • axios.post(url [,data [,config]])
  • axios.put(url [,data [,config]])
  • axios.patch(url [,data [,config]])

Be careful
When using the alias method , Don't need to config It is specified in url,method and data attribute .

Concurrent

Help functions handle concurrent requests .

  • axios.all(iterable)
  • axios.spread(callback)

Create examples

You can use custom configurations to create axios New examples .

axios.create([config])

1
2
3
4
5
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});

Example method

The available example methods are as follows . The specified configuration will be merged with the instance configuration .

axios#request(config)
axios#get(url [,config])
axios#delete(url [,config])
axios#head(url [,config])
axios#post(url [,data [,config]])
axios#put(url [,data [,config]])
axios#patch(url [,data [,config]])

Request configuration


These are the available configuration options for making requests . Only url It's necessary . If no method is specified , The request will default to GET.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
{
// `url` Is the server that will be used for the request URL
url: '/user',
 
// `method` Is the request method used when making the request
method: 'get', // Default
 
// `baseURL` Will be added to `url` front , Unless `url` Absolutely .
// It is convenient for axios Instance settings for `baseURL`, So that we can compare URL The method passed to the instance .
baseURL: 'https://some-domain.com/api/',
 
// `transformRequest` Allow changes to the request data before it is sent to the server
// This only applies to the request method 'PUT','POST' and 'PATCH'
// The last function in the array must return a string , One ArrayBuffer Or a Stream
 
transformRequest: [function (data) {
// Do any data conversion you want
 
return data;
}],
 
// `transformResponse` Allow in then / catch Change the response data before
transformResponse: [function (data) {
// Do whatever you want to transform the data
 
return data;
}],
 
// `headers` Is the custom to send headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
 
// `params` Is to be sent with the request URL Parameters
// Must be a pure object or URLSearchParams object
params: {
ID: 12345
},
 
// `paramsSerializer` It's an optional function , Responsible for serialization `params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
 
// `data` Is the data to be sent as the request body
// Only for request methods “PUT”,“POST” and “PATCH”
// When there is no setting `transformRequest` when , Must be one of the following types :
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: 'Fred'
},
 
// `timeout` Specifies the number of milliseconds before the request times out .
// If the requested time exceeds 'timeout', The request will be aborted .
timeout: 1000,
 
// `withCredentials` Indicates whether cross site access control requests
// should be made using credentials
withCredentials: false, // default
 
// `adapter' Allow custom processing requests , This makes testing easier .
// Return to one promise And provide an effective response ( See [response docs](#response-api))
adapter: function (config) {
/* ... */
},
 
// `auth' Indicates that the HTTP Basic authentication , And provide credentials .
// This will set up a `Authorization' head , Cover any existing `Authorization' Custom header , Use `headers` Set up .
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
 
// “responseType” Represents the type of data the server will respond to
// Include 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
 
//`xsrfCookieName` Is to be used as xsrf The value of the token cookie The name of
xsrfCookieName: 'XSRF-TOKEN', // default
 
// `xsrfHeaderName` It's carrying xsrf The token is worth http Name of head
xsrfHeaderName: 'X-XSRF-TOKEN', // default
 
// `onUploadProgress` Allow processing of uploaded progress Events
onUploadProgress: function (progressEvent) {
// Use local progress Events do whatever you want
},
 
// `onDownloadProgress` Allow processing of download progress Events
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
 
// `maxContentLength` Define what is allowed http Maximum size of response content
maxContentLength: 2000,
 
// `validateStatus` Defines whether to resolve or reject the given promise
// HTTP Response status code . If `validateStatus` return `true`( Or set to `null` promise Will be parsed ; otherwise ,promise Will be
  // Refuse .
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
 
// `maxRedirects` It's defined in node.js The maximum number of redirects to follow in .
// If set to 0, Will not follow redirection .
maxRedirects: 5, // Default
 
// `httpAgent` and `httpsAgent` Used to define in node.js Respectively http and https The custom agent to use when requesting .
// Allow configuration similar to `keepAlive` The option to ,
// Not enabled by default .
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
 
// 'proxy' Define the host name and port of the proxy server
// `auth` Express HTTP Basic auth Should be used to connect to the agent , And provide credentials.
// This will set up a `Proxy-Authorization` header, Cover any use `headers` Set the existing `Proxy-Authorization` Customize headers.
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},
 
// “cancelToken” Specifies the cancellation token that can be used to cancel the request
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}

Use then when , You will receive the following response :

1
2
3
4
5
6
7
8
axios.get('/user/12345')
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});

Configure defaults


You can specify the configuration defaults that will be applied to each request .

overall situation axios The default value is

1
2
3
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Custom instance defaults

1
2
3
4
5
6
7
// Set configuration defaults when creating instances
var instance = axios.create({
   baseURL:'https://api.example.com'
});
 
// Change the default value after instance creation
instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;

Configure priority order

Configuration will be combined with priority . The order is lib / defaults.js The library defaults in , And then there's the example defaults attribute , Finally, it is requested config Parameters . The latter will take precedence over the former . Here's an example .

1
2
3
4
5
6
7
8
9
10
11
12
// Create an instance using the configuration defaults provided by the library
// here , The timeout configuration value is `0`, This is the default value for the library
var instance = axios.create();
 
// Override the timeout defaults for the library
// Now all requests will wait before the timeout 2.5 second
instance.defaults.timeout = 2500;
 
// Override the timeout for this request , Because it knows it takes a long time
instance.get('/ longRequest',{
   timeout:5000
});

Interceptor


You can intercept requests or responses when they are then perhaps catch Before processing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Add a request interceptor
axios.interceptors.request.use(function(config){
     // Do something before sending a request
     return config;
   },function(error){
     // Do something when the request is wrong
     return Promise.reject(error);
   });
 
// Add response interceptors
axios.interceptors.response.use(function(response){
     // Do something about the response data
     return response;
   },function(error){
     // Do something when the request is wrong
     return Promise.reject(error);
   });

If you need to remove interceptors later .

1
2
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

You can add interceptors to axios Custom instance of .

1
2
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

Handling errors


1
2
3
4
5
6
7
8
9
10
11
12
13
14
axios.get('/ user / 12345')
   .catch(function(error){
     if(error.response){
       // Request sent , But the server responds with a status code
       // Fall in the 2xx Beyond the scope of
       console.log(error.response.data);
       console.log(error.response.status);
       console.log(error.response.headers);
     } else {
       // An error occurred while setting the request that triggered the error
       console.log('Error',error.message);
     }}
     console.log(error.config);
   });

You can use validateStatus Configuration options define custom HTTP Status code error range .

1
2
3
4
5
axios.get('/ user / 12345',{
   validateStatus:function(status){
     return status < 500; // Only if the status code is greater than or equal to 500 I refuse to
   }}
})

eliminate


You can use the cancel token to cancel the request .

axios cancel token API Based on cancellable promise proposal , It's in its infancy 1.

You can use CancelToken.source The factory creates a cancel token , As shown below :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
 
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// Handling errors
}
});
 
// Cancel the request ( The message parameter is optional )
source.cancel(' Operation cancelled by user .');

You can also pass the executor function to CancelToken Constructor to create the cancellation token :

1
2
3
4
5
6
7
8
9
10
11
12
var CancelToken = axios.CancelToken;
var cancel;
 
axios.get('/ user / 12345',{
   cancelToken:new CancelToken(function executor(c){
     // An actuator function takes a cancel function as an argument
     cancel = c;
   })
});
 
// Cancel the request
clear();

Be careful : You can cancel several requests with the same cancel token .

Use application / x-www-form-urlencoded Format


By default ,axios take JavaScript Object serialization to JSON. In the form of an application / x-www-form-urlencoded Format send data , You can use one of the following options .

browser

In the browser , You can use URLSearchParams API, As shown below :

1
2
3
4
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Please note that , None of the browsers support URLSearchParams, But there is one polyfill You can use ( Make sure polyfill Global environment ).

perhaps , You can use qs Libraries encode data :

1
2
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });

Node.js

stay node.js in , have access to querystring modular , As shown below :

1
2
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' });

You can also use qs library .

Promise


axios Rely on the machine to support ES6 Promise Realization . If your environment doesn't support ES6 Promises, You can use polyfill.

TypeScript


axios Include TypeScript Definition .

1
2
import axios from 'axios';
axios.get('/user?ID=12345');

axios To a great extent Angular Provided $http The inspiration of service . Final ,axios Try to provide a place in Angular Independent... For external use $http-like service .

axios More related articles on the whole strategy

  1. vue axios Total strategy

    No longer maintained vue-resource, And recommend that you use axios Start ,axios Be known by more and more people . Originally, I wanted to find a detailed strategy on the Internet , Suddenly found that ,axios The official document itself is very detailed !! What else can I do with this ...

  2. 【 turn 】axios Total strategy

    With vuejs The author, you Yuxi, released the news , No longer maintained vue-resource, And recommend that you use axios Start ,axios Be known by more and more people . Originally, I wanted to find a detailed strategy on the Internet , Suddenly found that ,axios The official script of ...

  3. axios The basic introduction and use of the whole strategy (GET And POST)

    axios axios It's based on Promise Of HTTP client , Specifically for browsers and node.js service Vue 2.0 Official recommendation axios To replace the original Vue request, So here ...

  4. 【C# Code combat 】 Ant colony algorithm theory and practice strategy —— A new method for route optimization problems such as traveling salesman problem

    When I was in graduate school a few years ago , There is a professor in the college , Specialized in ant colony algorithm , A bad , I know a little bit from time to time . Feeling is also a manifestation of biological intelligence , And genetic algorithms . Neural networks are similar . It's just that there was no real need to learn , So I didn't study . There's been one recently ...

  5. Generate PDF Total strategy 【2】 Already exist PDF Add content to

    Projects are changing , Demand is changing , It's always the programmer who hits the keyboard ..... PDF After generation , Sometimes you need to PDF Add something else to it , Like words , picture .... After several failed attempts , Finally got the right way to write code . Here it is ...

  6. The Pragmatic Programmer —— read 《Java Programmer career strategy 》 Feeling

    The Pragmatic Programmer —— read <Java Programmer career strategy > Feeling   <Java Programmer career strategy > It's in the form of a story , Introduce to the reader Java Professional experience of programmers . The author Niu Kaifu is engaged in software development in Beijing , It's already a ...

  7. Android Screen adaptation strategy ( Reprint )

    http://blog.csdn.net/jdsjlzx/article/details/45891551 https://github.com/hongyangAndroid/AndroidAuto ...

  8. Moon.Orm3.8 Technology strategy

    Moon.ORM Technology strategy   One . The introduction This article mainly aims at Moon.ORM Discussion of the technology and its use guidance . If you have any other questions , Please leave a message . This paper mainly aims at Moon.ORM3.9 edition , At the same time, it will be helpful to 4.0 Do a technical preview . This paper starts from ...

  9. TestLink Installation strategy

    TestLink Installation strategy This article is from the link --http://www.cnblogs.com/Tcorner/archive/2011/07/26/2117296.html Preparation before installation Need to download xam ...

Random recommendation

  1. stay webapi2 Use in OWIN Self boarding mode

    OWIN   To put it bluntly, the self boarding model doesn't need IIS 了 , Direct route access cs Mode of service I typed the official example again , First installation Microsoft.AspNet.WebApi.OwinSelfHost, Be careful not to install ...

  2. MFC Don't let programs appear on the taskbar

    If it's a dialog box, the program is directly in the dialog box On initialization , Modify the style ModifyStyleEx(WS_EX_APPWINDOW,WS_EX_TOOLWINDOW); But for multiple documents or single documents , There is no corresponding dialog style ...

  3. javascript The second basic study notes ( One )

    1. compatible xhtml Method : <script> //<![CDATA[ ... ... //]]> </script> 2. Document mode : IE5.5 introduce , Initially it contains 2 Kind of : mixed ...

  4. MD5 SHA-1 Example

    Test code public class SignatureUtils {     public static void main(String[] args) throws Exception {     ...

  5. You know JS Execution process ?

        As we know , When we write JS After procedure , Open the browser , Our code is ready to run ( Of course, make sure your code is OK , To do what you expect ). What I just said is JS A big environment for execution , Today we'll learn about , ...

  6. Asp.Net BulletedList Use and explain

    BulletedList Use and explain   Source of the article :www.cnblogs.com/xiohao/archive/2013/10/09/3359263.html BulletedList It's a place where you can relax in ...

  7. NodeJS Blocking / Non blocking

    Blocking instance var fs = require('fs'); var data = fs.readFileSync('test.txt') console.log(data.toString()); co ...

  8. C++ Primer Plus Reading notes

    cin Do text input Use cin The basic way to get characters char ch; cin >> ch; cin Read char Values, spaces and newlines are ignored . Besides , Send to cin The input of is buffered . This means that only when the user presses back ...

  9. for in and for of The difference between ( turn )

    Link to the original text :https://www.jianshu.com/p/c43f418d6bf0 1 Traversing arrays usually uses for loop ES5 You can also use forEach,ES5 Also has traversal array function map.filte ...

  10. recovery Enforce factory reset (Rescue Party)

    Sometimes when the system is working properly , Suddenly run to recovery Inside the , And stopped at the following interface :   Can't load Android system. Your data may be corrupt. If ...