axios库学习
axios库学习
1.npm安装axios
npm install axios --save
2.导入axios
import axios from 'axios'
3.使用
axios有以下特性:
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
3.1全局配置
可以通过全局配置,指定url服务器的域名,连接超时时间等等,通过全局配置了后,调用axios时无需再重新传入配置参数,默认会使用全局配置里面的配置信息。
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 2500;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
......
3.2get请求
语法:
axios.get(url[,config])
.then(function) //异步请求成功的回调
.catch(function) //异步请求失败的回调
示例:
//配置了全局参数baseURL后只需要写服务器路径名和提交参数
axios.defaults.baseURL = 'https://api.example.com';
//访问https://api.example.com/user?ID: 12345
//示例一:
axios.get('/user', {
//params查询参数
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//示例二:
axios.get('/user?ID: 12345')
.then(response => {console.log(response)};
)
.catch(error => {console.log(error)});
//示例三:
axios({
url:'/user',
method:'get',
params:{
//参数
ID: 12345
}
}).then(res =>{
console.log(res)
})catch(error => {
console.log(error)
});
3.3post请求
语法:
axios.post(url[, data[, config]])
.then(function) //异步请求成功的回调
.catch(function) //异步请求失败的回调
示例:
//示例一:
axios.post('/user', {
firstName: 'zhang',
lastName: 'san'
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
//示例二:
axios.({
url:'/user',
method:'post',
data:{
//post过去的数据
firstName: 'zhang',
lastName: 'san'
}
}).then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
3.4合并请求
有时有一些需求是:需要同时完成多个异步请求然后再进行回调
语法:
axios.all(iterable) //iterable为一个请求数组
.then(function) //异步请求成功的回调
.catch(function) //异步请求失败的回调
示例:
//示例一:
//请求一
function getUserAccount() {
return axios.get('/user/12345');
}
//请求二
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
//合并请求
//axios.spread可以拆分返回的回调结果
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
//示例二:
axios.all([axios.get('/user',params: {
ID: 12345
}),
axios.post('/user', data:{
//post过去的数据
firstName: 'zhang',
lastName: 'san'
})])
.then(axios.spread(function (data1, data2) {
// 两个请求现在都执行完成
console.log(f1)
console.log(f2)
}));
3.5创建axios实例
有时候我们可能会多个服务器发送请求,而每个服务器要求请求的配置信息有不相同,这时候我们可以使用axios.create来创建独立的axios实例,而不使用公共的axios实例。
语法:
const instance = axios.create([config]);
示例:
//返回一个axiospromise实例
const instance1 = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
const instance2 = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
});
//使用像axios一样
instance1.get('/user')
.then(data =>{{console.log(data)})
4.请求配置
这里我直接复制官方文档,只有 url
是必需的。如果没有指定 method
,请求将默认使用 get
方法。你可以对照这个官方文档来设置请求配置,比较常用的,如:method,baseURL,headers,params,data,timeout,responseEncoding,proxy等等
{
// `url` 是用于请求的服务器 URL
url: '/user',
// `method` 是创建请求时使用的方法
method: 'get', // default
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data, headers) {
// 对 data 进行任意转换处理
return data;
}],
// `transformResponse` 在传递给 then/catch 前,允许修改响应数据
transformResponse: [function (data) {
// 对 data 进行任意转换处理
return data;
}],
// `headers` 是即将被发送的自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是即将与请求一起发送的 URL 参数
// 必须是一个无格式对象(plain object)或 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` 时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 浏览器专属:FormData, File, Blob
// - Node 专属: Stream
data: {
firstName: 'Fred'
},
// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 1000,
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
// `adapter` 允许自定义处理请求,以使测试更轻松
// 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
// `auth` 表示应该使用 HTTP 基础验证,并提供凭据
// 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` 允许为下载处理进度事件
onDownloadProgress: function (progressEvent) {
// 对原生进度事件的处理
},
// `maxContentLength` 定义允许的响应内容的最大尺寸
maxContentLength: 2000,
// `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
// 如果设置为0,将不会 follow 任何重定向
maxRedirects: 5, // default
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null, // default
// `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
// `keepAlive` 默认没有启用
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: new CancelToken(function (cancel) {
})
}
5.响应信息
axios的response如下,当我们回调then中的函数时,我们可以通过response.data,response.status来获取response对应的信息。
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 服务器响应的头
headers: {},
// `config` 是为请求提供的配置信息
config: {},
// 'request'
// `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: {}
}
6.拦截器
我们对axios实例对象添加拦截器,在请求或响应被 then
或 catch
处理前拦截它们。如:
- 在request发起前拦截
- 在request发送失败后拦截
- 在response返回后拦截
- 在response返回失败时拦截
用法:
//请求拦截器
instance.interceptors.request.use()
//响应拦截器
instance.interceptors.response.use()
示例:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
//添加一个请求拦截器
instance.interceptors.request.use(config =>{
//请求发送前进行拦截
config.timeout=10000; //可以对请求config进行修改
return config; //一定要返回config
},err =>{
//请求失败后拦截
console.log(err)
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);
});
7.取消请求
你可以通过cancel token
来取消一个请求,axios.CancelToken是一个类,我们通过CancelToken.source()工厂方法创建一个实例。
示例:
var CancelToken = axios.CancelToken;
var source = CancelToken.source(); //调用工厂方法创建资源
//source.token是CancelToken实例,source.cancel是回调函数,可以看下面源码
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源码:
解析:
- 先看最下面的工厂函数,source()会先new CancelToken(function executor©),而CancelToken保存在token,而CancelToken的回调函数executor()会将c保存在cancel。
- CancelToken类要求传入一个函数executor,CancelToken的会先new Promise,并将Promise的resolve()函数交给CancelToken来管理。
- 然后CancelToken会执行executor()函数,并且executor()要求传入一个回调函数cancel,回顾一下前面的工厂函数,executor()的功能是将传入的参数传递给最外面的source对象,这时最外面的source就能控制executor()的回调。
- executor()里的回调函数会new Cancel(message),并且通过resolvePromise(token.reason);删除创建的Promise(function promiseExecutor(resolve)对象。
var Cancel = require('./Cancel');
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
结合示例进行思考:
这里重复一下上面的示例,结合源码思考一下,下面的操作是怎么实现的,我网上看过一些介绍,但是看得云里雾里,所以这里我自己重新总结了一下。
var CancelToken = axios.CancelToken;
var source = CancelToken.source(); //调用工厂方法创建资源
/*
这里创建的source有两个参数,从源码的工厂函数中可以知道:
{
token: token, //token里面是CancelToken实例
cancel: cancel //而cancel里面保存的是executor的回调
}
*/
/*
这里调用axios.get,当我们指定cancelToken: source.token时,
axios.get会使用CancelToken实例中的promise来发送请求,再看到最下面的cancel(),
从上面的源码可以看出,我们的这个cancel()对应的是删除cancelToken实例中的
promise,而axios.get会使用CancelToken实例中的promise,所以当我们调用
cancel()就会删除请求。
其实回想一下:CancelToken中的回调函数executor(c)的工作无非就是将删除操作的回调函数c,
丢给了最上层source.cancel来控制。无论CancelToken内部的promise如何,只有我通过
source.cancel来调用删除,那么CancelToken内部的promise就会被删除。
*/
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
// 删除请求
source.cancel('Operation canceled by the user.');
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)