1.基本API
axios.get()
axios.delete()
axios.post()
axios.put()
get与delete
<script>
// 为给定 ID 的 user 创建请求
axios.get/delete('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get/delete('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
post与put
<script>
// 发送的是JSON格式的数据
axios.post('/user', {
uname: "tom",
pwd: 123
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
//发送的是字符串的数据
var params = new URLSearchParams();
params.append("uname", "tom");
params.append("pws", "123")
axios.post('/user', params)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
2.请求配置
//配置默认地址,之后的请求都将拼接这个地址
axios.defaluts.baseURL = "http://localhost:3000/"
//请求超时时间
axios.defaluts.timeout = 3000
//自定义请求头
axios.defaluts.headers["mytoken"] = "123"
3.拦截器
// 添加请求拦截器
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);
});