// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
// Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
// 统一处理request让测试更加容易 // 返回一个promise并提供一个可用的response // 其实我并不知道这个是干嘛的!!!! // (see lib/adapters/README.md). adapter: function (config) { /* ... */ },
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. auth: { username: 'janedoe', password: 's00pers3cret' },
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default
// 处理上传进度事件 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event },
// 处理下载进度事件 onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event },
// 设置http响应内容的最大长度 maxContentLength: 2000,
// 定义可获得的http响应状态码 // return true、设置为null或者undefined,promise将resolved,否则将rejected validateStatus: function (status) { return status >= 200 && status < 300; // default },
// `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. // 最大重定向次数?没用过不清楚 maxRedirects: 5, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' defines the hostname and port of the proxy server // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. // 代理 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } },
// `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) // 用于取消请求?又是一个不知道怎么用的配置项 cancelToken: new CancelToken(function (cancel) { }) }
// 添加一个请求拦截器 axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); });
// 添加一个响应拦截器 axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); });
如果之后想移除拦截器你可以这么做
1 2
var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
你也可以为axios实例添加一个拦截器
1 2
var instance = axios.create(); instance.interceptors.request.use(function () {/*...*/});
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } })
// cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelTokenconstructor:
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 executor function receives a cancel function as a parameter cancel = c; }) });
// cancel the request cancel();
Note: you can cancel several requests with the same cancel token.
Using application/x-www-form-urlencoded format
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.
Browser
In a browser, you can use the URLSearchParams API as follows:
1 2 3 4
var params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);
Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).
Alternatively, you can encode data using the qs library:
1 2
var qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 }));
Node.js
In node.js, you can use the querystring module as follows:
1 2
var querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
Until axios reaches a 1.0 release, breaking changes will be released with a new minor version. For example 0.5.1, and 0.5.4 will have the same API, but 0.6.0 will have breaking changes.
Promises
axios depends on a native ES6 Promise implementation to be supported. If your environment doesn’t support ES6 Promises, you can polyfill.
axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.