Vue前端通过Axios的post方式传输数据,后端为什么一直接收的值是null?
·
沃靠!这个细节太细了,搞了我两个多小时才找到这个bug。
一、
首先官方文档给我的post请求的例子是这样的:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
二、
我的请求参数很简单,就是username和password(用来做测试用的,简单不好i嘛!)然后我这样写上去,并且后端单纯就先用对应的
axios.post('/test2', {
username: 'Fred',
password: 'Flintstone'
},{
headers: {
"Content-Type": "application/json;charset=utf-8",
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
@PostMapping("/test2")
public void test2(String username,String password){
System.out.println("测试2接收的数据="+users.getUsername()+" pwd="+users.getPassword());
}
好的!接收的值=null 错的很惨!
三、
后来我觉得可能是没有封装成对象的问题,于是再改!
axios.post('/test2', {
users:{
username:'12',
password:'111'
}
},{
headers: {
"Content-Type": "application/json;charset=utf-8",
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
@PostMapping("/test2")
public void test2(@RequestBody users users){
System.out.println("测试2接收的数据="+users.getUsername()+" pwd="+users.getPassword());
}
还是null 错!
四、
这次终于对了!参数还是对象,只不过在外面定义,users(和后端一样的名称)或者别的啥都可以!
const users=ref({
username:name,
password:pwd
})
axios.post('http://localhost:8080/user/test2',users.value,{
headers: {
"Content-Type": "application/json;charset=utf-8",
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
@PostMapping("/test2")
public void test2(@RequestBody users users){
System.out.println("测试2接收的数据="+users.getUsername()+" pwd="+users.getPassword());
}
更多推荐
所有评论(0)