前言
params是添加到url的请求字符串中的,一般用于get请求。
data是添加到请求体(body)中的, 一般用于post请求。
上面,只是一般情况. 其实,post请求也可以使用params方式传值 , 但是get请求没有data方式,本文就来介绍一下post的两种传值方式
Axios 中posts的params与data的两种传参
第一种:data方式
1 2 3 4 5 6 7 8 9 10 11 12 13 | this.$axios({ url: '/api/user/login' , method: 'post', headers: { 'Content-Type': 'application/json' }, data:{ username: this.user, pwd: this.pwd } }).then((res) => { console.log(res) }) |
第二种:params方式
1 2 3 4 5 6 7 8 9 10 11 12 13 | this.$axios({ url: '/api/user/login' , method: 'post', headers: { 'Content-Type': 'application/json' }, params:{ username: this.user, pwd: this.pwd } }).then((res) => { console.log(res) }) |
注:直接使用post方法,传递的参数为 data 的方式
代码如下:
1 2 3 4 5 6 7 | this.$axios.post('/api/user/login',{username: this.user, pwd: this.pwd }), { headers: { 'Content-Type': 'application/json' } }).then((res) => { console.log(res) |
使用场景
一般,情况下都是使用data的传参方式,但有时会发现需要使用params的方式,后台才能获取到数据,这与后台的接口有关,我们前端不能控制。如Java接口
若使用Map接收参数,必须使用
@RequestParam 修饰。但是如果想传list 类型的数据,需要使用单独的方法处理(参考链接)。若使用
data 传递参数,必须使用一个实体类接收参数,而且需要添加注解@RequestBody 进行修饰作者:somliy
链接:https://www.jianshu.com/p/7a24b5eed364
作者:doubleyong
公众号:bug收集
博客:bugshouji.com (专门解决与收集bug的网站)