Axios is a Promise-based HTTP library that can be used in browsers and Node.js.
Github is at github.com/axios/axios
Installation method
Use the CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code
or
< script SRC = "https://cdn.staticfile.org/axios/0.18.0/axios.min.js" > < / script >Copy the code
Use NPM:
$ npm install axios
Copy the code
Using bower:
$ bower install axios
Copy the code
Using yarn:
$ yarn add axios
Copy the code
Usage:
Vue.axios.get(api).then((response) => {
console.log(response.data)
})
this.axios.get(api).then((response) => {
console.log(response.data)
})
this.$http.get(api).then((response) => {
console.log(response.data)
})
Copy the code
Browser Support
The GET method
We can simply read JSON data:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script src="https://unpkg.com/vue@next"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> {{info}} </div> <script> const app = {data() {return {info: 'Ajax test!! '}}, mounted () { axios .get('https://www.runoob.com/try/ajax/json_demo.json') .then(response => (this.info = response)) .catch(function (error) {console.log(error); }); } } Vue.createApp(app).mount('#app') </script> </body> </html>Copy the code
Use Response.data to read JSON data:
<! DOCTYPE HTML > < HTML > <head> <meta charset=" UTF-8 "> <title>Vue test instance </title> <script src="https://unpkg.com/vue@next"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <h1> <div v-for="site in info" > {{site.name}} </div> </div> <script> const app = { Data () {return {info: 'Ajax test!! '}}, mounted () { axios .get('https://www.runoob.com/try/ajax/json_demo.json') .then(response => (this.info = Response.data.sites). Catch (function (error) {console.log(error); }); } } Vue.createApp(app).mount('#app') </script> </body> </html>Copy the code
The GET method passes parameters in the following format:
ID=12345 axios.get('/user? ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); Get ('/user', {params: {ID: 12345}}). Then (function (response) {console.log(response); }) .catch(function (error) { console.log(error); });Copy the code
POST method
new Vue({ el: '#app', data () { return { info: null } }, mounted () { axios .post('https://www.runoob.com/try/ajax/demo_axios_post.php') .then(response => (this.info = Response). Catch (function (error) {console.log(error); }); }})Copy the code
The POST method passes parameters in the following format:
Axios. post('/user', {firstName: 'Fred', // firstName lastName: 'Flintstone' // lastName}). Then (function (response) {console.log(response); }) .catch(function (error) { console.log(error); });Copy the code
Execute multiple concurrent requests
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) {// Both requests are now executed}));Copy the code
axios API
The request can be created by passing the relevant configuration to AXIOS.
Axios (config) // Send the POST request axios({method: 'POST ', url: '/user/12345', data: {firstName: 'Fred', lastName: 'Flintstone' } }); Axios ({method:' GET ', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .then(function(response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); Axios (url[, config]) // Send GET request (default method) axios('/user/12345');Copy the code
Alias of the request method
Aliases are provided for all supported request methods for ease of use. Aliases can be used to initiate requests:
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]])
Copy the code
Note: When using alias methods, url, method, and data attributes do not have to be specified in the configuration.
concurrent
Helper functions for handling concurrent requests:
axios.all(iterable)
axios.spread(callback)
Copy the code
Create an instance
You can create a new axiOS instance using a custom configuration:
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Copy the code
Instance methods
The following example methods are available. The specified configuration is merged with the configuration of the instance:
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]])
Copy the code
Request configuration item
Below are the configuration options available when creating the request, noting that only the URL is required. If method is not specified, the request uses the get method by default.
{// 'url' is the server URL used for the request url: "/user", // 'method' is the method used to create the request method: "Get ", // the default is get // baseURL will automatically precede the URL unless the url is an absolute URL. // It can facilitate passing the relative URL baseURL to axios instance methods by setting a 'baseURL' : "https://some-domain.com/api/", // 'transformRequest' allows Modify request data // Can only be used with "PUT", "POST" and "PATCH" request methods // The function in the following array must return a string, either an ArrayBuffer, or a Stream transformRequest: [function (data) {// return data; }], // 'transformResponse' allows modification of response data before passing it to then/catch: [function (data) {return data;}], headers: {" x-requested-with ": "XMLHttpRequest"}, // 'params' is the URL parameter to be sent with the request // Must be a plain object or URLSearchParams object params: {ID: 12345}, / / ` paramsSerializer ` is a ` params ` serialization functions / / (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 that is sent as the request body // only applies to these request methods "PUT", "POST", and "PATCH" // When no' transformRequest 'is set up, must be one of the following types: // -string, plain Object, ArrayBuffer, ArrayBufferView, URLSearchParams Stream data: {firstName: "Fred"}, // 'timeout' specifies the number of milliseconds for the request to timeout (0 indicates no timeout) // If the request takes longer than timeout, the request will be interrupted. 1000, // 'withCredentials' indicates whether credentials withCredentials are needed in cross-domain requests: False, // The default // 'adapter' allows custom processing of requests to make testing easier // Return a promise and apply a valid response (see [Response docs](#response-api)). Adapter: function (config) { /* ... */}, // 'auth' indicates that HTTP base authentication should be used and credentials provided // This sets an Authorization header that overrides any existing custom Authorization header set using 'headers' : { username: "janedoe", password: "S00pers3cret"}, // 'responseType' indicates the data type of the server response, Can be "arrayBuffer ", "blob", "document", "json", "text", "stream" responseType: "Json ", // default // 'xsrfCookieName' is the name of the cookie used as the value of the XSRF token xsrfCookieName: "Xsrf-token ", // default // 'xsrfHeaderName' is the name of the HTTP header that carries the value of the XSRF TOKEN xsrfHeaderName: "X-xsrf-token ", // the default // 'onUploadProgress' allows the upload progress event onUploadProgress to handle: Function (progressEvent) {// Handle native progress events}, // 'onDownloadProgress' allows handling progress events for downloads: Function (progressEvent) {// handle native progress events}, // 'maxContentLength' defines the maximum size of the response content allowed. 2000, // 'validateStatus' defines a resolve or reject PROMISE for a given HTTP response status code. If 'validateStatus' returns' true' (or is set to 'null' or 'undefined'), promises will be resolved; If not, promise should be rejecte validateStatus: function (status) {return status > = 200 & & status < 300; // 'directs' specifies the maximum number of redirects to follow in node.js. 5, // the default // 'httpAgent' and 'httpsAgent' are used in Node.js to define custom agents used when performing HTTP and HTTPS, respectively. // 'keepAlive' is not enabled by default httpAgent: new http.Agent({keepAlive: true}), httpsAgent: new https.Agent({ keepAlive: True}), // "proxy" defines the host name and port of the proxy server // 'auth' indicates that HTTP basic authentication should be used to connect to the proxy and provide credentials // This will set a 'proxy-authorization' header, Overrides the existing custom 'proxy-authorization' header set using 'header'. Proxy: {host: "127.0.0.1", port: 9000, auth: : {username: "mikeymike", password: "Rapunz3l"}}, // 'cancelToken' specifies the cancel token used to cancel the request // (see the Cancellation section below for more information) cancelToken: new CancelToken(function (cancel) { }) }Copy the code
Response of the structure
The response to the AXIos request contains the following information:
Data: {}, // 'status' HTTP status code status: 200, //' statusText 'HTTP status information from the server response statusText: "OK", // 'headers' server response headers: {}, //' config 'is the configuration information for the request config: {}}Copy the code
When you use then, you receive the following response:
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);
});
Copy the code
A response can be used via an error object when a catch is used or when a Rejection callback is passed as the second argument to a THEN.
Default value configured
You can specify configuration defaults that will be used on individual requests.
The global AXIos default value:
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';
Copy the code
Default value for custom instance:
Var instance = axios.create({baseURL: 'https://api.example.com'}); / / after the instance has been created to modify the default instance.defaults.headers.com mon [' Authorization '] = AUTH_TOKEN;Copy the code
Configuration priority
Configurations are merged in a priority order. The order is: the library defaults found in lib/defaults.js, then the instance defaults property, and finally the requested Config parameters. The latter will take precedence over the former. Here’s an example:
Var instance = axios.create(); var instance = axios.create(); / library/override a timeout defaults / / now, before the timeout, all requests will be waiting for 2.5 second instance. The defaults. Timeout = 2500; // Set instance.get('/longRequest', {timeout: 5000}) for requests known to take a long time to override.Copy the code
The interceptor
Intercepts requests or responses before they are processed by THEN or catch.
/ / add request interceptor axios. Interceptors. Request. Use (function (config) {/ / what to do before sending a request return config. }, function (error) {return promise.reject (error); }); / / add the response interceptor axios. Interceptors. Response. Use (function (response) {/ / do something to return the response to the response data; }, function (error) {return promise.reject (error); });Copy the code
If you want to remove interceptors later, you can do this:
var myInterceptor = axios.interceptors.request.use(function () {/*... * /}); axios.interceptors.request.eject(myInterceptor);Copy the code
You can add interceptors for custom AXIOS instances.
var instance = axios.create(); instance.interceptors.request.use(function () {/*... * /});Copy the code
Error handling:
Axios.get ('/user/12345'). Catch (function (error) {if (error. Response) { But the status code of the server response is not in the 2xx range console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });Copy the code
You can use the validateStatus configuration option to define an error range for a custom HTTP status code.
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; Reject {reject}})Copy the code
cancel
Cancel the request using the Cancel token.
Axios’ Cancel Token API is based on Cancelable Promises Proposal
The cancel token can be created using the canceltoken. source factory method like this:
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 {// handle error}}); // Cancel the request (the message argument is optional) source.cancel('Operation Canceled by the user.');Copy the code
CancelToken can also be created by passing an executor function to the CancelToken constructor:
var CancelToken = axios.CancelToken; var cancel; axios.get('/user/12345', { cancelToken: New CancelToken(function executor(c) {// The executor function accepts a cancel function as an argument cancel = c; })}); // Cancel the request cancel();Copy the code
Note: You can cancel multiple requests using the same Cancel token.
Application/X-www-form-urlencoded is used for requests
Axios serializes JavaScript objects as JSON by default. If you want to use the Application/X-www-form-urlencoded format, you can use the following configuration.
The browser
In the browser environment, you can use the URLSearchParams API:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
Copy the code
URLSearchParams is not supported by all browsers.
In addition, you can use the QS library to encode data:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
// Or in another way (ES6),
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
Copy the code
Node. Js environment
In Node.js, you can use the QueryString module:
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
Copy the code
Of course, like the browser, you can also use the QS library.
Promises
Axios relies on the native ES6 Promise implementation to be supported.
If your environment doesn’t support ES6 Promises, you can use Polyfill.
TypeScript support
Axios contains TypeScript definitions.
import axios from "axios"; axios.get("/user? ID=12345");Copy the code