今天在写登录功能时,axios发送请求报错Required String parameter 'paramter' is not present
我的后台代码参数是这样的
@RequestParam("username") String username,
@RequestParam("password") String password,
前端发送axios请求的代码是这样的
this.$http({
this.$http({
method: 'post',
url: '/auth/accredit' ,
data: {
password:this.loginForm.password,
username:this.loginForm.username
}
这样竟然会有400,找不到参数的错误.
在查看Content-Type为application/json;charset=UTF-8
我们的参数是 JSON 对象,而查看axios源码会发现它会自动帮我们做一个stringify 的处理。
使用axios发送请求时,直接把 json 数据放到请求体中传递给后端
显然这就与我们服务器要求的 @RequestParam和
Content-Type:
application/x-www-form-urlencoded不匹配了。
解决方法
使用 URLSearchParams 传递参数
let param = new URLSearchParams()
param.append('username', this.loginForm.username)
param.append('password', this.loginForm.password)
this.$http({
method: 'post',
url: '/auth/accredit' ,
data: param
}).then((res) => {
this.$message.success("登录成功!");
})
.catch((err) => {
this.$message.error(err);
});
}