axios异步访问后台 @RequestParam 获取参数 HTTP Status 400 - Required String parameter 'xx' is not present

axios 异步请求三种方式

1、Content-Type: application/json

后台使用@RequestBody

获取参数

import axios from 'axios'
let data = {code:'123',name:'yyyy'};
axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log('res=>',res);            
})

2、Content-Type: multipart/form-data

后台使用HttpServletRequest request 

获取参数

import axios from 'axios'
let data = new FormData();
data.append('code','1234');
data.append('name','yyyy');
axios.post(`${this.$url}/test/testRequest`,data)
.then(res=>{
    console.log('res=>',res);            
})

3、Content-Type: application/x-www-form-urlencoded

import axios from 'axios'
import qs from 'Qs'
let data = {'code':'234','name':'yyyy'};
axios.post(`${this.$url}/testRequest`,qs.stringify({
    data
}))
.then(res=>{
    console.log('res=>',res);            
})

后台接收参数写法

@PostMapping("testRequest")
public String resetPwd( String code, String name) {
        System.out.println(code);
        return "xxx";
    }

如果使用@RequestParam 则需要这样写

  @PostMapping("testRequest")
    public String testRequest(@RequestParam(value = "code",required = false) String code, @RequestParam(value = "name", required = false) String name) {
        System.out.println(code);
        return "dfdfdfd";
    }

总结:
application/x-www-form-urlencoded请求是表单请求,可以用@RequestParam一个一个获取参数,当Content-Type == application/json 前端传来的是json串,用@RequestParam是获取不到的,需要用@RequestBody将json串华为对

posted @ 2020-05-14 10:04  随★风  阅读(1104)  评论(0编辑  收藏  举报