axios常用的四个方法:
- get:查询数据
- post:添加数据
- put:修改数据
- delete:删除数据
1.get传递参数
①通过URL传递参数
第一种:通过问号进行传参
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
})
获取参数用query.id
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id)
})
第二种:直接加参数进行传参
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
获取参数用params.id
app.get('/axios/:id', (req, res) => {
res.send('axios get (Restful) 传递参数' + req.params.id)
})
改变的两处细节:
注:
如果使用直接传参,在接收参数时要加上“:id”
②通过params选项传递参数
this.axios.get('http://127.0.0.1:8080/new/findSomeNews',{
params:{
typeId:1,
start:0,
number:7
}
}).then(res=>{
if(res.data.code == 1){
this.list = res.data.data;
console.log(this.list);
}
});
2.delete传递参数(同get相同)
3.post传递参数
①通过选项传递参数(默认传递的是json格式的数据)
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
使用body.xxx获取参数:
app.post('/axios', (req, res) => {
res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd)
})
②通过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)
})
4.put传递参数
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
axios的响应结果
- data:实际相应回来的数据
- headers:响应头信息
- status:响应状态码
- statusTxet:响应状态信息
axios拦截器
1.请求拦截器
//添加一个请求拦截器
axios.interceptors.request.use(function(config) {
//请求发出之前设置一些信息
console.log(config.url)
config.headers.mytoken = 'nihao';
//这里必须返回config,这样才能够完成拦截器的功能
return config;
}, function(err){
//这里处理响应的错误信息
console.log(err)
})
2.响应拦截器
axios.interceptors.response.use(function(res) {
// 在这里对返回的数据进行处理
//res不是真正的数据,data才是真正的数据
var data = res.data;
return data;
}, function(err){
//这里处理响应的错误信息
console.log(err)
})