接口调用axios的用法
首先引入
axios.get('http://localhost:3000/adata').then(function(ret){
// 注意data属性是固定的用法,用于获取后台的实际数据
// console.log(ret.data)
console.log(ret)
})
get传递参数
- 通过url传递参数
- 通过params选项传递参数
如下代码:
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
})
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
delete的传参方式和get的差不多
url restful风格的url params传参
axios delete 请求传参
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
post 传递参数
通过选项传递参数(默认传递的是json格式的数据)
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
后台接收的时候数据是req.body.uname等形式的
post也可以传递表单形式的数据
通过URLSearchParams传递参数
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
put的传递方式和post的类似
post和put都支持两种格式的传参,一种是json一种是传统的表单形式的数据传递
axios拦截器
- 请求拦截器
例子:
- 响应拦截器
例子:
参考的黑马程序员视频 https://www.bilibili.com/video/BV1vE411871g?p=89