【axios】API 说明
基于promise用于浏览器和node.js的http客户端
特点
- 支持浏览器和node.js
- 支持promise
- 能拦截请求和响应
- 能转换请求和响应数据
- 能取消请求
- 自动转换JSON数据
- 浏览器端支持防止CSRF(跨站请求伪造)
浏览器支持
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |
安装使用
//npm $ npm install axios
//cdn引用 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
示例
执行get请求
// 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); });
执行post请求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); Performing 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 complete }));
axios API
Requests can be made by passing the relevant config to axios
.
axios(config) // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); // GET request for remote image 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 a GET request (default method) axios('/user/12345');
请求方法别名
为了方便我们为所有支持的请求方法均提供了别名。
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
说明
When using the alias methods url
, method
, and data
properties don't need to be specified in config.
Concurrency
Helper functions for dealing with concurrent requests.
axios.all(iterable)
axios.spread(callback)
Creating an instance
You can create a new instance of axios with a custom config.
axios.create([config])
Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
Request Config
These are the available config options for making requests. Only the url
is required. Requests will default to GET
if method
is not specified.
Response Schema
The response for a request contains the following information.
When using then
, you will receive the response as follows:
When using catch
, or passing a rejection callback as second parameter of then
, the response will be available through the error
object as explained in the Handling Errors section.
Config Defaults
You can specify config defaults that will be applied to every request.
Global axios defaults
Custom instance defaults
Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults
property of the instance, and finally config
argument for the request. The latter will take precedence over the former. Here's an example.
拦截器
You can intercept requests or responses before they are handled by then
or catch
.
If you may need to remove an interceptor later you can.
You can add interceptors to a custom instance of axios.
错误处理
You can define a custom HTTP status code error range using the validateStatus
config option.
Cancellation
You can cancel a request using a cancel token.
The axios cancel token API is based on the withdrawn cancelable promises proposal.
You can create a cancel token using the CancelToken.source
factory as shown below:
You can also create a cancel token by passing an executor function to the CancelToken
constructor:
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:
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:
Node.js
In node.js, you can use the querystring
module as follows:
You can also use the qs
library.
Semver
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.
TypeScript
axios includes TypeScript definitions.
Resources
Credits
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.
License
MIT