一、介绍
包,能发ajax,返回promise
本质是函数,函数用法,对象用法。
npm i axios -S
二、三种参数
1、params路径参数
属于路径的一部分
axios当中参数只能写在路径中,没有params设置
axios({
url:'http://sdfsdfdsfsd/8?name="zhangsan"'
// 8是一个参数 一般是id,传给后台
})
2、query参数
//(1)直接写在url后
?q=v& sort=stars
//(2)使用配置项parmas配置
axios({
url:'',
params:{
q:'v',
sort:'starts'
}
}
3、请求体参数
向后台提交数据用的,post put 请求体中使用
data参数,配置项data当中去配置
axios({
url:'',
data:{
firstName:"Fred",
lastName:"Flintstone"
}
}
三、基本使用
1、函数用法
<button class="btn btn-primary" onclick="sendGET()"> 发送GET请求 </button>
// http://127.0.0.1/server?a=100&b=200
<script>
function sendGET(){
axios({
//是配置对象
//请求的类型
method: 'GET',
//URL设置
url: 'http://127.0.0.1/server',
//参数
params: {
//配的是query参数
a:100,
b:200
},
//设置请求头信息 查询字符串
headers: {
c:300,
d:400
}
}).then(response => {
console.log(response);
});
}
</script>
2、对象用法
axios.get(url[, config]) //get请求用于列表和信息查询
axios.delete(url[, config]) //删除
axios.post(url[, data[, config]]) //post请求用于信息的添加
axios.put(url[, data[, config]]) //更新操作
<div class="container">
<button class="btn btn-warning" onclick="sendPOST()"> 发送POST请求 </button>
<script>
function sendPOST(){
axios.post('http://127.0.0.1/server', 'e=500&f=600', {
params: {a:100,b:200},
headers: {c:300,d:400}
}).then(response => {
console.log(response);
})
}
</script>
3、默认配置
作用:简化代码
axios.defaults.baseURL = 'http://127.0.0.1';
axios.defaults.method = 'GET';
axios.defaults.timeout = 3000;//超时时间
axios({
url: '/server',
}).then(response => {
console.log(response);
})
axios({
method:'POST',
url: '/json-server',
}).then(response => {
console.log(response);
})
4、创建实例
创建实例,封装不同的接口请求
//one和two的使用方式一样
const one = axios.create({
baseURL : 'http://www.bd.com',
method: 'GET',
});
const two = axios.create({
baseURL: 'http://www.jd.com',
method: "POST"
});
one({
url: '/s',
}).then(response => {
console.log(response);
});
two({
url: '/home',
}).then(response => {
console.log(response);
})
5、取消请求
<button>点击发送</button>
<button>点击取消</button>
<script>
let btns = document.querySelectorAll('button');
//获取CanelToken函数
// let CancelToken = axios.CancelToken;
//1. 声明变量
let c = null;
//
btns[0].onclick = function () {
axios({
//请求方法
method: 'POST',
//URL
url: 'http://127.0.0.1/delay-server',
//取消请求配置
cancelToken: new axios.CancelToken(function (cancel){
//2. 赋值
c = cancel;
}),
}).then(response => {
console.log(response);
})
}
//绑定事件
btns[1].onclick = function(){
//3. 运行 c 函数
c();
}
</script>
四、拦截器
只做两件事:干预请求头和响应体、添加额外功能
1、请求拦截器
请求发出之前的钩子,对你的请求进行干预
一般情况下,只去处理成功的,因为几乎不会失败。
// interceptor属性,request也是属性,use方法,参数两个函数,两个函数叫做拦截器
// 第一个函数是成功的回调,第二个是失败的回调
axios.interceptors.request.use(function (config) {
//config 就是配置对象
config.params.a = 100;
config.params.b = 200;
config.headers = {
auth: 'a1231231231293012o'
}
return config;
},
function (error) {
return Promise.reject(error);
});
axios.interceptors.request.use(function (config) {
//要求必须要有 id 参数
if (config.params && config.params.id) {
//1. 如果参数 OK 则返回 config
return config;
} else {
//2. 如果参数有误, 则返回失败的Promise对象, 阻止请求的发送
return Promise.reject('参数缺失');
}
}, function (error) {
return Promise.reject(error);
});
2、响应拦截器
在响应之前发出的钩子,对你的响应进行干预。
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});
五、 二次封装
// 二次封装axios
//1、引入
import axios from 'axios'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
//2、用axios创建新的实例 进行二次封装
// 创建实例,封装不同接口请求
const instance = axios.create({
//配置基础路径和超时限制
baseURL: '/api', // 配置基础路径
timeout: 20000
})
//3、请求拦截器和响应
//拦截器只干两件事:修改报文 添加额外功能
//添加进度条功能 npgross -安装js和css
instance.interceptors.request.use((config) => {
//请求拦截器一般都只是处理成功的
let userTempId = store.state.user.userTempId
if(userTempId){
config.headers.userTempId = userTempId
}
//每次请求带上用户的登录标识
let token = store.state.user.userInfo.token
if(token){
config.headers.token = token
}
//开启进度条
Nprogress.start()
return config
})
//响应拦截器
instance.interceptors.response.use(
//成功的回调
(response) => {
//直接返回数据(不返回响应报文)
//关闭进度条
Nprogress.done()
return response.data
},
//失败的回调
(error) => {
//统一处理请求错误,具体请求也可以选择处理和不处理
Nprogress.done()
alert('请求失败'+ error.message || '未知错误')
//中断promise链 返回pending状态
return new Promise(() => {})
}
)
export default instance