axios 是什么
axios 是基于promise 用于浏览器和 node.js 是 http 客户端
axios 的作用
axios 主要是用于向后台发送请求的,还有在请求中做更多是可控功能
特点:
- 支持浏览器和 node.js
- 支持promise
- 能拦截请求和响应
- 能转换请求和响应数据
- 能取消请求
- 自动转换JSON数据
- 浏览器支持防止 CSRF/XSRF(跨站请求伪造)
promise 是什么
promise 是一个对象用来传递异步操作的信息,它代表了某个未来才会知道结果的时间(通常是一个异步操作),并且这个事件提供系统的api,可提供一步的处理
promise 的作用
promise的出现主要是解决地狱回调的问题,比如你需要请求很多个接口,这些接口的参数需要另外那个的接口返回的数据作为依赖,这样就需要我们一层嵌套一层,但是有了promise我们就无需嵌套
promise 的本质是什么
分离异步数据获取和业务
安装
$ npm install axios
举个栗子
执行一个 get 请求
const axios = require('axios')
// 向具有给定的id 的用户发出请求
axios.get('/user?ID=12345').then(function(response){
// 响应success
console.log(response)
}).catch(function(error){
// 响应 error
console.log(error)
}).then(function(){
// always executed
})
// 上面的请求也可以通过下面 params 传递参数的方式实现
axios.get('/user',{
params:{
ID:12345
}
}).then(function(response){
console.log(response)
}).catch(function(error){
console.log(error)
}).then(function(){
// always executed(总是执行)
})
// 添加 async 关键字到函数/方法前面就行
async function getUser(){
try{
const response = await axios.get('/user?ID=12345')
console.log(response)
} catch(error){
console.log(error)
}
}
执行一个 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){
// 两个请求现已完成
}))
拦截器
在请求或响应被 then 或 catch 处理前拦截它们(拦截器你可以做什么:在请求或者响应时拦截下来进行处理)
拦截器分为请求拦截器和响应拦截器
- 请求拦截器(interceptors.requst)是指可以拦截每次或指定 HTTP 请求,并可修改配置项
- 响应拦截器(interceptors.response)可以在每次HTTP请求后拦截住每次或指定HTTP请求,并可修改返回结果向
// 添加请求拦截器
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)
})
移除拦截器
var myInterceptor = axios.interceptors.request.use(function(){})
axios.interceptors.request.eject(myInterceptor)