安装
npm insatll axios
使用CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
例子
执行一个GET
请求
// 向具有给定ID的用户发出请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
//可选地,上面的请求也可以作为
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
// 想要使用异步/等待?将`async`关键字添加到你的外部函数/方法。
async function getUser() {
try {
const response = await axios.get('/user?ID=12345')
console.log(response)
} catch (error) {
console.error(error)
}
}
注意:async / await是ecmascript 2017的一部分,在Internet Explorer和旧版浏览器中不支持,所以请谨慎使用。
执行一个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((acct, perms) => {
// Both requests are now complete
}))
axios API
请求可以通过将相关配置传递给axios来完成。
axios(config)
// 发送一个POST请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// GET 请求一个远程img
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
}).then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
})
axios(url[, config])
// 发送一个GET请求(默认方法)
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]])
注意:当使用别名方法时,url,method和data属性不需要在config中指定。
并发
帮助函数用于处理并发请求。
axios.all(iterable)
axios.spread(callback)
创建一个实例
您可以使用自定义配置创建一个新的axios实例。
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
})
实例方法
下面列出了可用的实例方法。指定的配置将与实例配置合并。
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]])
请求配置
这些是提出请求的可用配置选项。只有
URL
是必须的。如果未指定methods
请求默认为GET
{
// `url`是将用于请求的服务器URL
url: '/user',
// `method`是提出请求时要使用的请求方法
method: 'get', // default
// 除非`url`是绝对的,`baseURL`将被预置为`url`。
// 为axios的实例设置`baseURL`可以方便地将相对URL传递给该实例的方法。
baseURL: 'https://some-domain.com/api/',
// `transformRequest`允许在请求数据发送到服务器之前对其进行更改
// 这仅适用于请求方法'PUT','POST'和'PATCH'
// 数组中的最后一个函数必须返回一个字符串或Buffer,ArrayBuffer的实例,
// FormData或Stream
// 您可以修改标题对象。
transformRequest: [function (data, headers) {
// 做任何你想要改变数据的东西
return data;
}],
// `transformResponse`允许在传递给then / catch之前对响应数据进行更改
transformResponse: [function (data) {
// 做任何你想要改变数据的东西
return data;
}],
// `headers`是自定义头文件
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params`是要与请求一起发送的URL参数
// 必须是普通对象或URLSearchParams对象
params: {
ID: 12345
},
// `paramsSerializer`是一个负责序列化`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`是要作为请求主体发送的数据仅适用于请求方法'PUT','POST'和'PATCH'
// 如果没有设置`transformRequest`,则必须是以下类型之一:
// - 字符串,普通对象,ArrayBuffer, ArrayBufferView, URLSearchParams
// - 仅限浏览器:FormData,File,Blob
// - 仅节点: Stream, Buffer
data: {
firstName: 'Fred'
},
// `timeout`指定请求超时之前的毫秒数。 如果请求花费的时间超过“timeout”,请求将被中止。
timeout: 1000,
// `withCredentials`指示是否应该使用凭证进行跨站点访问控制请求
withCredentials: false, // default
// `adapter`允许自定义处理请求,使测试变得更容易。返回一个promise并提供有效的响应 (see lib/adapters/README.md).
adapter: function (config) {
/* ... */
},
// `auth`表示应该使用HTTP基本认证,并提供证书。 这将设置一个`Authorization`头,用`headers`覆盖已经设置的任何现有`Authorization`自定义头。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType`指示服务器将响应的数据类型是'arraybuffer','blob','document','json','text','stream'
responseType: 'json', // default
// `responseEncoding`指示用于解码响应的编码
// 注意:对'stream'的'responseType'或客户端请求忽略
responseEncoding: 'utf8', // default
// `xsrfCookieName`是用作xsrf标记值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName`是携带xsrf标记值的http标头的名称
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress`允许处理上传的进度事件
onUploadProgress: function (progressEvent) {
// 做任何你想要的本地进展事件
},
// `onDownloadProgress`允许处理下载的进度事件
onDownloadProgress: function (progressEvent) {
// 做任何你想要的本地进展事件
},
// `maxContentLength`定义了以字节为单位的http响应内容的最大大小
maxContentLength: 2000,
// `validateStatus`定义是否解析或拒绝给定HTTP响应状态码的Promise。 如果`validateStatus`返回`true`(或者被设置为`null`或`undefined`),则Promise将被resolved; 否则,Promise将被rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects`定义node.js中要遵循的最大重定向次数。 如果设置为0,则不会遵循重定向。
maxRedirects: 5, // default
// `socketPath`定义了一个在Socket.js中使用的UNIX套接字。
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// 只能指定`socketPath`或`proxy`。 如果两者都指定,则使用`socketPath`。
socketPath: null, // default
// `httpAgent`和`httpsAgent`定义了一个自定义代理,分别在node.js中执行http和https请求时使用。 这允许添加选项,如`keepAlive`,默认情况下不启用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy'定义代理服务器的主机名和端口使用`false`来禁用代理,忽略环境变量.
// `auth`表示应该使用HTTP Basic认证来连接代理,并提供证书。这将设置一个`Proxy-Authorization`标头,覆盖您使用标头设置的任何现有的`Proxy-Authorization`自定义标头。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken`指定一个取消令牌,可以用来取消请求
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}
响应模式
对请求的响应包含以下信息。
{
// `data`是服务器提供的响应
data: {},
// `status`是服务器响应中的HTTP状态码
status: 200,
// `statusText`是来自服务器响应的HTTP状态消息
statusText: 'OK',
// `headers`服务器响应的标题
// 所有标题名称都是小写
headers: {},
// `config`是为请求提供给`axios`的配置
config: {},
// `request`是产生这个响应的请求
// 它是node.js中的最后一个ClientRequest实例(在重定向中)和浏览器的XMLHttpRequest实例
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或将拒绝回调作为第二个参数传递时,响应将通过错误对象提供,如处理错误部分中所述。
配置默认值
您可以指定将应用于每个请求的配置默认值。
全局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'
自定义实例默认值
// 在创建实例时设置配置默认值
const instance = axios.create({
baseURL: 'https://api.example.com'
})
// 在创建实例后修改默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN
配置优先顺序
配置将与优先顺序合并。
顺序是lib / defaults.js中的库缺省值,然后是实例的defaults属性,最后是请求的config参数。
后者将优先于前者。
这里是一个例子。
// 使用库提供的配置默认值创建一个实例
// 此时,超时配置值为库的默认值“0”
const instance = axios.create()
// 覆盖库的超时默认值
// 现在所有使用此实例的请求都会在超时前等待2.5秒
instance.defaults.timeout = 2500
// 覆盖此请求的超时时间,因为它已知需要很长时间
instance.get('/longRequest', {
timeout: 5000
})
拦截器
你可以在用
then
或catch
处理它们之前拦截请求或响应。
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做一些事情
return config;
}, function (error) {
// 错误之后做的一些事情
return Promise.reject(error);
});
// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
// 用响应数据做一些事情
return response;
}, function (error) {
// 错误之后做的一些事情
return Promise.reject(error);
});
如果以后可能需要删除拦截器。
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
您可以将拦截器添加到axios的自定义实例。
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
处理错误
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// 该请求已完成,服务器使用状态码进行响应
// 超出2xx的范围
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 该请求已作出,但没有收到任何答复
// `error.request`是浏览器中的XMLHttpRequest实例,node.js中的http.ClientRequest实例
console.log(error.request);
} else {
// 设置触发错误的请求时发生了一些情况
console.log('Error', error.message);
}
console.log(error.config);
});
您可以使用validatestatus config选项定义自定义http状态码错误范围。
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // 仅当状态码大于或等于500时才拒绝
}
})
消除
您可以使用取消令牌取消请求。
axios取消令牌API基于撤回的可取消承诺提案。
您可以使用canceltoken.source工厂创建取消标记,如下所示:
const CancelToken = axios.CancelToken;
const 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
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// 取消请求(消息参数是可选的)
source.cancel('Operation canceled by the user.');
您还可以通过将执行程序函数传递给canceltoken构造函数来创建取消标记:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// 执行程序功能接收取消功能作为参数
cancel = c;
})
});
// 取消请求
cancel();
注意:您可以使用相同的取消标记取消多个请求。
使用application / x-www-form-urlencoded格式
默认情况下,axios将JavaScript对象序列化为JSON。 要以application / x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。
Browser
在浏览器中,您可以使用URLSearchParams API,如下所示:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
请注意,所有浏览器都不支持urlsearchparams(请参阅caniuse.com),但可以使用polyfill(确保填充全局环境)。
或者,您可以使用qs库编码数据:
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
或以另一种方式(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);