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());
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜到极致就是渣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值