如何解决@RequestParam无法接收vue+axios传递json数据

axios的post请求无法发送到后端

1.问题 : axios的post的传递的json数据无法接收

​ 问题背景:SpringBoot+Vue测试开发项目前后端联调,发现axios的post请求向后端传递的参数,后台无法收到。

2.问题代码

 public CommonResult TestDriver(
            @RequestParam(value = "tests",required = false)String test_txt,
    ) throws IOException {

​ 后台controller可以被触发,但是无法接收到参数"tests",required = true 时就报body中无tests。

 axios.post(url,{"tests":this.input_tests}).then((info)=>{
       this.input_tests=this.input_tests + "/n" + info.data.data
})

3.问题归因

​ test_txt 是空值无法接收到。这就涉及到了Content-Type问题,@RequestParam 这种用postman测试可以得到正确结果,但是我没有注意到请求是application/x-www-form-urlencoded 形式的。

​ 但是通过分析axios源码发现前端传的数据是json格式的,所以数据格式应该是application/json格式的。

4.问题解决

    @RequestMapping(value = "/getToken",method = RequestMethod.POST,consumes = "application/json;charset=UTF-8")
    @ResponseBody
    public CommonResult testExcute(
            @RequestBody JSONObject jsonObject
            ){
      
        String test_txt =jsonObject.getString("tests");  

5.查漏补缺

​ RequestBody 接收的是请求体里面的数据;

​ RequestParam接收的是key-value

 public CommonResult getServe(
            HttpServletRequest request,
            @RequestParam(value = "cid",required = false)Integer cid,
            @RequestParam(value = "url",required = true)String url,
            @RequestParam(value = "name",required = false)String name,
            @RequestParam(value = "method",required = false)String method,
            @RequestParam(value = "type",required = false)String type
    ) throws IOException {

​ 如果参数时放在请求体中,application/json传入后台要用@RequestBody才能接收到。

​ 我发现之前组员的项目中用到过这种写法

@PostMapping(value="/login",consumes = "application/json;charset=UTF-8")
    public String login(@RequestBody User user) throws Exception{}

​ 这种参数是一个对象的写法,并且用@RequestBody修饰的,前后端连接时需要满足一些要求。

​ @RequestBody修饰的类,json字符串的key值对应实体类的值,也就是user的name对应json数组"name"的值。

​ @RequestBody修饰的类,json字符串的key值对应实体类的值,也就是user的name对应json数组"name"的值。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>