Axios简介
axios前端异步请求库类似JQuery ajax技术,
ajax用来在页面发起异步请求到后端服务,并将后端服务响应数据渲染到页面上,
jquery推荐ajax技术,但vue里面并不推荐在使用jquery框架,vue推荐使用axios异步请求库。
axios总结:
- 用来在前端页面发起一个异步请求,请求之后页面不动,响应回来刷新页面局部;
- 官方定义: axios 异步请求库并不是vue官方库第三方异步库在vue中推荐axios;
- 特点:易用、简洁且高效的http库 —> 发送http异步请求库。
Axios功能&特性
- 从浏览器中创建XLHttpRequests从 node.js 创建http请求(发送axios异步请求)
- 支持Promise API
- 拦截请求和响应(做拦截器)
- 转换请求数据和响应数据取消请求
- 自动转换JSON数据,客户端支持防御XSRF
常规使用
发送Get请求,查询:
axios.get("http://localhost:8081/demo?id=21&name=xiaowang ").then( function(res){
//代表请求成功之后处理
console.1og (res.data);
}).catch( function (err){
//代表请求失败之后处理
alert ('进入catch ')
console.log (err);
});
// 为给定 ID 的 user 创建请求
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);
});
发送POST,添加
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
其他请求
axios.put(.then( ).catch ( ); //修改
axios.patch( ).then( ).catch( );
axios.delete( "ur1?id=21").then ( ).catch ( ); //删除
Axios的封装
import axios from 'axios'
export default function axios(option){
return new Promise((resolve,reject) => {
//1.创建sxios实例
const instance = axios.create({
url: 'api',
timeout: 5000,
headers: ''
})
//2.传入对象进行网络请求
instance(option).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
}
Axios创建默认实例发送请求
//创建axios的配置对象
var instance = axios. create({
baseURL: 'http://localhost:8081/', //基础路径,后面的请求的url就直接写接口路径就行
timeout: 5000,
});
这里的请求地址,直接写对应的接口路径
instance.get("/demo?id=21&name=xiaowang ").then( function(res) {
//代表请求成功之后处理
console.log(res);
console.1og (res.data);
}).catch( function (err) {
//代表请求失败之后处理
alert ('进入catch ');
console.log (err);
});
Axios封装一个request请求
export function request(config, success, failure) {
// 1.创建axios的实例
const instance = axios.create({
baseURL: 'http://127.0.0.1:8080',
timeout: 5000
})
// 发送真正的网络请求
instance(config).then(res => {
success(res);
}).catch(err => {
failure(err)
})
}
Axios拦截器
请求拦截器
请求拦截器作用是在发出请求时,拦截下用户的请求,执行完一系列处理再发送出去(像添加cookie、token,请求头等)
配置请求拦截器
- 首先创建一个axios实例对象
import axios from 'axios'
import { ELMessage } from 'element-plus'
const myRequest = axios.create({
baseURL: process.env.BASE_API, // 这里可以写自己访问的地址,例如127.0.0.1
timeout: 3000, // 请求超时时间
headers: {
"Content-Type": "application/json;charset=utf-8"
}
})
- 接下来就是配置请求拦截器(interceptor.request)
myRequest.interceptors.request.use(
req=>{...}, // 对发起的请求进行处理,方法写在{}中,req是请求参数
err=>{...}, // 出现请求错误时进行的处理
}
下面写一个设置token的实例:
myRequest.interceptors.request.use(
config => {
const token = localStorage.getItem('token') // 获取存取的token
if(token){ // 不为空的话就设置进headers
config.headers['token'] = token
}
return config
},
err => {
return Promise.reject(error)
}
)
响应拦截器
配置响应拦截器
myRequest.interceptors.response.use(
res=>{...}, // 对响应进行处理,方法写在{}中,res是返回数据
err=>{...}, // 出现请求错误时进行的处理
)
假如服务器的响应为:
{
"errCode" : 0,
"errDesc" : "Success",
"data": "xxxxxx"
}
这时候我们可以这样写响应拦截器:
myRequest.interceptors.response.use(
res => {
if(res.errCode == 0){
return Promise.resolve(res.data)
}
else {
ElMessage({
message: "Error",
type: 'error',
duration: 5 * 1000
})
return Promise.reject(new Error("Error Message"))
}
},
err => {
ElMessage({
message: err.data.message,
type: 'error',
duration: 5 * 1000
})
}
)
通过上面的处理之后,我们axios.xxx().then((res)=>{…})的res就为响应数据的data,其中errCode和errDesc就被处理掉了。