axios是基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
axios使用:
- 界面引入 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- axios配置:
// 配置method方式 axios({}) .then(function(response){}) .catch(function(error){}) // get方式 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); }); // 同时发起多个请求 axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // 两个请求都完成才执行 }));
{} 请求配置:
// request请求配置
{
url: '/user', // 请求的接口地址
method: 'get', // 请求的方法,'get'(默认值)、'post',
baseURL: 'https://some-domain.com/api/', // 拼接url(不是绝对路径)作为请求的接口地址
// 最后一个函数需return出相应数据
transformRequest: [function (data, headers) { // 修改请求前data和header
headers['Authority'] = 'token xxxx';//处理header token
return data;// 可以对data做任何操作
}],
// 对接口回来数据进行处理,它会传给then或者catch
transformResponse: [function (data) {
return data; // 可以对data做任何操作
}],
headers: { // 发送的自定义请求头
'X-Requested-With': 'XMLHttpRequest', // 异步,null为同步
'Content-Type': 'application/x-www-form-urlencoded', // 数据会以普通表单形式(键值对)发送到后端 useName='xc'&lastName='li','application/json'(json字符串的形式发送到后端{useName: 'xc'}),'multipart/form-data'(文件上传格式)
},
// 拼接到请求url,跟data一样,data用于post方法,params用于get方法
params: {
id: ’13‘
},
// 是一个可选的函数负责序列化`params`
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data: { // 请求数据,post方法使用,当没有设置`transformRequest`时,必须是以下几种格式
firstName: 'Fred'
},
timeout: 1000, // 请求超时时间(毫秒)
withCredentials: false, // 是否携带cookie信息,默认为false
auth: { // HTTP 基础验证并提供凭据,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
username: 'janedoe',
password: 's00pers3cret'
},
responseType: 'json', // 响应格式,默认值是json
onUploadProgress: function (progressEvent) { // 处理上传进度事件
// Do whatever you want with the native progress event
},
onDownloadProgress: function (progressEvent) { // 处理下载进度事件
// Do whatever you want with the native progress event
},
maxContentLength: 2000,// 设置http响应内容的最大长度
validateStatus: function (status) { // 定义可获得的http响应状态码,return true、设置为null或者undefined,promise将resolved,否则将rejected
return status >= 200 && status < 300; // default
},
maxRedirects: 5, // default,最大重定向次数
proxy: { // 代理,本地可以跨域访问其他的网站 ,后端可配置Access-Control-Allow-Origin达到跨域
host: '127.0.0.1', // 将请求地址转变为此地址
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
cancelToken: new CancelToken(function (cancel) {}) // 用于取消请求
}
{} 响应配置:
{
data: {}, // 服务器提供的响应
status: 200, // 来自服务器响应的 HTTP 状态码
statusText: 'OK', // 来自服务器响应的 HTTP 状态信息
headers: {}, // 服务器响应的头
config: {}, // 是为请求提供的配置信息
request: {}
}
then接收响应信息:
.then(function(response) {
console.log(response.data); // 响应数据
console.log(response.status); // 响应状态
console.log(response.statusText); // 状态信息
console.log(response.headers); // 响应头
console.log(response.config); // 配置
});
catch错误处理:
.catch(function (error) {
if (error.response) {
// 错误结构与then结构一样
console.log(error.response.data); // 错误数据
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 发送请求但是没有响应返回
console.log(error.request);
} else {
// 其他错误
console.log('Error', error.message);
}
console.log(error.config);
});
拦截,在then和catch之前拦截请求和响应:
// 添加一个请求拦截器
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);
});
axios HTTP 客户端详解:Promise、拦截器与配置
本文详细介绍了axios库的使用,包括基于Promise的API、浏览器与Node.js环境的支持、请求与响应拦截器、各种请求方法如GET和POST的用法、配置选项如transformRequest和transformResponse,以及错误处理。此外,还涵盖了axios的请求配置,如URL、基础URL、请求头、数据序列化、超时和响应配置等,以及响应结构。最后,讨论了如何添加请求和响应拦截器来处理额外逻辑。

被折叠的 条评论
为什么被折叠?



