axios(三)

简介: 有时需要同时向服务端发起多个请求,这可以利用axios库提供的并发请求助手函数来实现

并发请求

有时需要同时向服务端发起多个请求,这可以利用axios库提供的并发请求助手函数来实现

代码如下:

function getUserAccount(){
return axios.get('url')
}
function getUserPermissions(){
return axios.get('url')
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread(function (acct,perms){
}))

acctgetUserAccount()方法请求的响应结果

permsgetUserPermissions()方法请求的响应结果

创建实例

可以使用自定义配置调用axios.create([config])方法来创建一个axios实例,之后使用该实例向服务器发起请求,就不用每次请求是重复设置配置选项了

代码如下:

const instance=axios.create({
baseURL:url,
timeout:1000,
headers:{'X-Custom-Header':'foobar'}
})

配置默认值

对于每次请求相同的配置选项,可以通过配置选项设置默认值来简化代码的编写。项目中使用到的全局axios默认值可以在项目的入口文件main.js中进行配置

代码如下:

axios.defaults.baseURL = 'url'
axios.defaults.headers.common['Authorzaiion']=AUTH_TOKEN
axios.defaults.headers.post['Content-Type']='application/x-www-from-urlencoded'
axios.defaults.withCredentials=true

也可以在自定义实例中设置配置默认值,这些配置选项只有在使用该实例发起请求时才生效。

代码如下:

//创建实例时设置默认值
const instance=axios.create({
    baseURL:URL
})
//实例后设置配置默认值
instance.defaults.headers.common['Authorizaiion']=AUTH_TOKEN

拦截器

有时需要统一处理http的请求和响应,axios拦截器的使用

代码如下:

添加请求拦截器

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)
})

自定义的axios实例添加拦截器

const instance=axios.create()
instance.interceptors.request.use(function(config){
    return config
},function(error){
    return Promise.reject(error)
})

移除拦截器

const myInterceptor=axios.interceptors.request.use(function(config){
    return config
},function(error){
    return Promise.reject(error)
})
axios.interceptors.request.eject(myInterceptor)

服务端通信的axios库的使用已经讲完了,该库的使用并不复杂,不过由于需要服务端提供数据访问接口,没有代码演示

目录
相关文章
|
6月前
|
XML JSON 前端开发
Axios的特点
Axios的特点
33 0
|
11天前
|
XML 存储 JSON
Axios
Axios
14 0
|
13天前
|
JSON 前端开发 JavaScript
axios的详细使用
axios的详细使用
51 1
|
13天前
|
JSON 前端开发 API
axios使用
axios使用
|
13天前
|
存储 设计模式 JSON
快速理解 Axios
快速理解 Axios
47 0
|
13天前
|
前端开发 JavaScript
Axios有哪些常用的方法?
Axios有哪些常用的方法?
36 0
|
7月前
axios详解
axios详解
52 0
|
8月前
|
JSON JavaScript 前端开发
axios的简单的使用
axios的简单的使用
40 0
|
9月前
axios
文章目录 引入 post请求 get请求 实例
35 0
|
9月前
axios学习
axios学习

热门文章

最新文章