axios 教程文档 中英文对照翻译
2017-05-25 10:29
513 查看
axios
Promise based HTTP client for the browser and node.js
基于浏览器和nodejs的http客户端 的promise
Features | 特色
Make XMLHttpRequests from the browser |在浏览器中创建XMLHttpRequestMake http requests from node.js |通过node创建http请求
Supports the Promise API |支持Promise Api
Intercept request and response |截取request和response
Transform request and response data |转换request和response的数据
Cancel requests |取消请求
Automatic transforms for JSON data 自动转json数据
Client side support for protecting against XSRF|客户端支持防范XSRF??
Browser Support | 浏览器支持
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |
Installing 安装
Using npm:$ npm install axios
Using bower:
$ bower install axios
Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Example | 例子
Performing aGETrequest
get请求的例子
// Make a request for a user with a given ID // 创建一个请求来获取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); });
Performing a
POSTrequest
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 toaxios.
可以通过配置来发送请求
axios(config)
// Send a POST request // 发送一个post 的请求 axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// GET request for remote image // get远程图片的请求 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');
Request method aliases| 请求方式 重命名
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.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
NOTE|小贴士
When using the alias methods
url,
method, and
dataproperties don’t need to be specified in config.
//用上面的方法 里面的
url,
method, 和
data的属性不需要写到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实例axios.create([config])
var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
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 theurlis required. Requests will default to
GETif
methodis not specified.
下列是创建请求的可用选项,url是必须的,默认请求使用get方法
{ // `url` is the server URL that will be used for the request // 用来请求的服务器地址 必填 url: '/user', // `method` is the request method to be used when making the request // 请求的方式 默认get method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // 如果url不是绝对地址 ,baseURL会放到它前面 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. // 可以设置到axios实例里面 baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // 发送请求前修改数据 // This is only applicable for request methods 'PUT', 'POST', and 'PATCH' // 只对'PUT', 'POST', 和 'PATCH'有效 // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // 数组里面的最后一个方法必须有返回 可以是string,instance of Buffer,ArrayBuffer, FormData 或 Stream transformRequest: [function (data) { // Do whatever you want to transform the data // 对你的数据为所欲为 return data; }], // `transformResponse` allows changes to the response data to be made before // 修改返回数据 // it is passed to then/catch // 传递给then/catch transformResponse: [function (data) { // Do whatever you want to transform the data // 对你的数据为所欲为 return data; }], // `headers` are custom headers to be sent // 设置请求头 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // 额 URl参数 和请求一起发送 // Must be a plain object or a URLSearchParams object // 一定要是plain object或是URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // 序列化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 // data作为请求主体发送 // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // 只有'PUT', 'POST', 和 'PATCH' 有用 // When no `transformRequest` is set, must be of one of the following types: // 没有设置transformRequest,必须符合以下的类型: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // `timeout` specifies the number of milliseconds before the request times out. // 设置超时 参数毫秒 // If the request takes longer than `timeout`, the request will be aborted. // 超时即终止请求 timeout: 1000, // `withCredentials` indicates whether or not cross-site Access-Control requests // 是否跨域请求 // should be made using credentials // 需要设置证书 withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // 适配器?? 自定义处理请求 方便测试 // Return a promise and supply a valid response (see lib/adapters/README.md). // 返回一个promise,并且提供验证返回,不懂跳文档(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' }, // `responseType` indicates the type of data that the server will respond with // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' // 指定返回类型 默认json responseType: 'json', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token // xsrf token的cookiename xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value // xsrf token的HeaderName xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads // 处理文件上传 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads // 处理文件下载 onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content allowed // 返回内容的最大长度 maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. //对response返回的状态进行验证 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. // 允许设置一些选项 keepAlive不是默认的 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server // `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 // 支持取消token 可以用来取消request // (see Cancellation section below for details) // (详情看下面) cancelToken: new CancelToken(function (cancel) { }) }
Response Schema | 响应的组成
The response for a request contains the following information.响应的内容包含以下信息
{ // `data` is the response that was provided by the server // 服务器响应数据 data: {}, // 状态码 // `status` is the HTTP status code from the server response status: 200, // 状态信息 // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased // 请求头 headers: {}, // `config` is the config that was provided to `axios` for the request // axios的请求配置 config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser // 请求主体 request: {} }
When using
then, you will receive the response as follows:
你在then里面可以用下面的信息
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); });
When using
catch, or passing a rejection callback as second parameter of
then, the response will be available through the
errorobject as explained in the Handling Errors section.
你用catch 或者 第二参数是拒绝回调的then的时候,response通过error对象像上面一样通过 Handling Errors部分展示
Config Defaults | 设置默认配置
You can specify config defaults that will be applied to every request.你可以设置默认配置 作用在所有的请求中
Global axios defaults | 全局axios的默认配置
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 | 单个实例的默认配置
// Set config defaults when creating the instance // 创建实例时设置配置默认值 var instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created // 实例创建后修改配置 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Config order of precedence | 配置的优先级
Config will be merged with an order of precedence. The order is library defaults found inlib/defaults.js, then
defaultsproperty of the instance, and finally
configargument for the request. The latter will take precedence over the former. Here’s an example.
设置配置不同时候的优先级,最低是
lib/defaults.js中的默认配置,然后是实例中的default属性,最后是请求主体的
config
// Create an instance using the config defaults provided by the library // 使用库提供的配置默认值创建一个实例 // At this point the timeout config value is `0` as is the default for the library // 在超时配置值为“0”时,采用库的默认值 var instance = axios.create(); // Override timeout default for the library // Now all requests will wait 2.5 seconds before timing out // 实例的默认超时时间 中级 instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time // 在请求是设置 最高级 instance.get('/longRequest', { timeout: 5000 });
Interceptors | 拦截
You can intercept requests or responses before they are handled bythenor
catch.
找 then和catch之前你可以拦截req和res的数据并处理
// Add a request interceptor // 在请求的时候拦截 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); });
If you may need to remove an interceptor later you can.
你用完了想取消拦截
var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.
你可以添加拦截到一个单独的axios实例中
var instance = axios.create(); instance.interceptors.request.use(function () {/*...*/});
Handling Errors | 错误处理
axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx // 服务器返回2xx以外的状态码 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js // 没有获得响应 console.log(error.request); } else { // Something happened in setting up the request that triggered an Error // 设置request的时候发生了一些错误 console.log('Error', error.message); } console.log(error.config); });
You can define a custom HTTP status code error range using the
validateStatusconfig option.
可以用
validateStatus自定义错误情况返回
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } })
Cancellation
You can cancel a request using a cancel token.你可以使用cancel token取消一个请求
The axios cancel token API is based on the withdrawn cancelable promises proposal.
axios 的cancel token api 是基于 cancelable promises 提案
You can create a cancel token using the
CancelToken.sourcefactory as shown below:
你可以使用
CancelToken.source这个工厂函数来创建一个cancel token :
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 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:
你也可以传递一个 executor function 给
CancelToken来创建一个cancel token
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 // executor 方法接受一个cancel 方法作为参数 cancel = c; }) }); // 取消请求 cancel();
Note: you can cancel several requests with the same cancel token.同一个cancel token可以取消多个请求
Using application/x-www-form-urlencoded format | 用 application/x-www-form-urlencoded 格式化
By default, axios serializes JavaScript objects toJSON. To send data in the
application/x-www-form-urlencodedformat instead, you can use one of the following options.
在默认情况下,axios 序列化js对象为‘json’ ,要格式化发送的数据你可以使用下面的数据
Browser | 浏览器
In a browser, you can use theURLSearchParamsAPI as follows:
在浏览器中,你可以使用URLSearchParams
var params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);
Note that
URLSearchParamsis not supported by all browsers, but there is a polyfill available (make sure to polyfill the global environment).| URLSearchParams 不支持所有的浏览器, 但是有polyfill可以用(确保polyfill在全局环境中)
Alternatively, you can encode data using the
qslibrary:
其他方法 你可以使用qs来格式化数据
var qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 }));
Node.js
In node.js, you can use thequerystringmodule as follows:
在nodejs中,你可以如下使用querystring:
var querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
You can also use the
qslibrary.
你也可以使用qs库。
Semver | 版本更新说明
Until axios reaches a1.0release, breaking changes will be released with a new minor version. For example
0.5.1, and
0.5.4will have the same API, but
0.6.0will have breaking changes.
axios达到1.0版本前,破坏性的更改将会使用新的小版本发布。例如0.5.1和0.5.4将具有相同的API,但0.6.0将有突破性的变化
Promises
axios depends on a native ES6 Promise implementation to be supported.If your environment doesn’t support ES6 Promises, you can polyfill.
axios 基于原生的ES6 Promise 实现,其他情况用polyfill
TypeScript
axios includes TypeScript definitions.axios 包含了TypeScript的定义
import axios from 'axios'; axios.get('/user?ID=12345');
相关文章推荐
- [Java文档翻译] Collections Framework Overview 集合框架概览 (中英文对照)
- 翻译官方开发文档ArcGIS Server ArcObjects API(中英文对照)
- NetBeans中文社区文档/教程翻译项目
- NetBeans中文社区文档/教程翻译项目
- MongoEngine文档翻译__新手教程(二)定义文档
- React中文教程翻译文档 - JSX Syntax(语法)
- React中文教程翻译文档 - Common Questions 常见问题
- [中英文对照]常见大学课程名称翻译
- Aircrack-ng官方文档翻译[中英对照]---Airmon-ng
- #android-ndk-r8d 使用 独立 编译 工具链 官方文档 中英文 对照
- Bottle文档最新翻译版-1.1一个简单的小教程
- android api 完整翻译之Contacts Provider (学习安卓必知的api,中英文对照)
- 中国各类基金资助项目英文翻译(中英文对照)
- HTML4.01规范中英文对照-HTML文档展现(1)
- 微积分英文词汇,高数名词中英文对照,高等数学术语英语翻译一览
- MongoEngine文档翻译__新手教程(一)安装MongoEngine&连接MongoDB
- NetBeans中文社区文档/教程翻译项目
- freetype2中英文对照教程
- H264规范 中英文对照参考文档
- MongoEngine文档翻译__新手教程(四)查询数据库