轴
为浏览器和节点提供基于 HTTP 客户端的承诺
特征
- 制作 XMLHttp 请求 从浏览器中
- 制作 网页 来自节点.js的请求
- 支持 答应 API 密码
- 拦截请求和答复
- 变换请求和响应数据
- 取消请求
- JSON 数据的自动转换
- 客户端保护支持 预算外
浏览器支持
![]() | ![]() | ![]() | ![]() | ![]() | ![]() |
|---|---|---|---|---|---|
| 最近的报告 | 最近的报告 | 最近的报告 | 最近的报告 | 最近的报告 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
安装
使用 npm :
$ npm install axios
使用弓箭手 :
$ bower install axios
使用 cdn :
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
示例
执行a 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);
});
执行a POST 请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行多项并行请求
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
}));
轴 API
可通过将相关配置传递给 axios。 。 。 .
axios( 配置)
// 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 [, 配置] )
// Send a GET request (default method)
axios('/user/12345');
请求方法别名
为方便起见,为所有支持的请求方法提供了别名.
axios. request( 配置)
arxios.get(url[,配置])
arxios.delete(url [, config]) (韩语)
axios.head(url [, config]) (中文(简体) )
axios. options( url[, config] ) (韩语)
axios.post(url[,数据[,配置]])
axios.put(url[,数据[,配置]])
axios.patch(url[,数据[,配置]])
页:1
使用别名方法时 url, (中文(简体) ), method,以及 data 属性不需要在配置中指定.
货币
处理同时提出的请求的助手职能.
axios.all(可渗出)
axios.spread(回调)
创建实例
您可以用自定义配置创建新 arxios 实例 .
axios.create([配置])
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
实例方法
现有实例方法如下。 指定的配置将会与实例配置合并 .
axios# 请求( 配置)
axios# get( url [, 配置] )
axios#delete(url[, config]) (韩语)
axios# head( url [, 配置])
axios# 选项( url[, 配置])
axios# post( url[, 数据[, 配置] ])
axios# put( url[, 数据 [, 配置] ]) )
axios# patch( url [, 数据 [, 配置] ]) )
请求配置
这些是可用于提出请求的配置选项。 只有 url 需要时间。 请求将默认为 GET 若为 method 未指定.
{
// `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
method: 'get', // default
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
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'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest: [function (data, headers) {
// 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
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
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
},
// `paramsSerializer` is an optional function in charge of serializing `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 applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - 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).
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'
responseType: 'json', // default
// `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` 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.
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) {
})
}
反应Schema
对请求的答复载有下列资料.
{
// `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
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: {}
}
使用时 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);
});
使用时 catch,或通过 拒绝回调 作为第二个参数 then,答复将通过 error 所解释的对象 处理出错 节.
配置默认值
您可以指定适用于每个请求的配置默认值.
全球轴默认值
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';
自定义实例默认值
// 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;
位次顺序
将合并为优先级。 命令是库默认值 lib/defaults.js,则 defaults 财产,最后 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
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
});
截取器
在请求或答复被处理之前,您可以截获请求或答复 then 或者说 catch。 。 。 .
// 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);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
如果你以后需要移除一个拦截器的话.
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
您可以在自定义的轴上添加截取器 .
var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
处理出错
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
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
console.log('Error', error.message);
}
console.log(error.config);
});
您可以使用 : validateStatus 配置选项 .
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
取消
您可以使用 取消签名。 。 。 .
轴取消符号 API 是基于撤回的 可取消的承诺提案。 。 。 .
您可以使用 CancelToken.source 如下所示:
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.');
您也可以通过将执行器函数传递到 CancelToken 构造器 :
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();
注意: 您可以用相同的取消令牌取消多个请求 .
使用应用程序/x-www-form-urlencoded格式
默认情况下, Axios 序列化 JavaScript 对象为 JSON中发送数据 application/x-www-form-urlencoded 格式,您可以使用以下选项之一.
浏览器
在浏览器中,您可以使用 URLSearchParams API如下:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
请注意:
URLSearchParams不为所有浏览器所支持(参见 caniuse.com (英语)),但有一个 多边填充 可用(确保全球环境的多填充).
或者,您可以使用 qs 库 :
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
节点.js
在节点.js,你可以使用 querystring 模块如下:
var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
你也可以使用这个 qs 图书馆.
塞姆维尔
直到轴线达到 1.0 发布时,会以一个新的小版本发布断开的更改. 举个例子 0.5.1,以及 0.5.4 将拥有相同的API,但 0.6.0 会有突破性变化.
承诺
axios 取决于本地ES6 承诺的执行 支持。 。 。 . 如果你的环境不支持ES6承诺,你可以 多边填充。 。 。 .
类型脚本
axios 包括 类型脚本 定义.
import axios from 'axios';
axios.get('/user?ID=12345');
资源
贷项
axios的灵感很大 http服务 提供情况 角质. 归根结底是努力提供独立的 $http- 像是Angular以外的服务.
许可证
麻省理工学院





