Uncaught (in promise) Error: Request failed with status code 415
错误如下图
前端代码(vue):
var data = {username: this.loginForm.username,password: this.loginForm.password}this.$axios.post(this.GLOBAL.host + '/login', this.$qs.stringify(data)).then(res => {// Determine the login status based on the returned resultsconsole.log(res)})
后台代码(springboot):
@Controller
public class LoginController {@Autowiredprivate LoginService loginService;@RequestMapping(value = "/login",method = RequestMethod.POST)@ResponseBodypublic Object login(@RequestBody UserDTO userDTO){return loginService.login(userDTO.getUsername(),userDTO.getPassword());}
}
错误原因:
当我们使用application / x-www-form-urlencoded时,Spring并不将其理解为RequestBody。因此,如果我们想要使用它,我们必须删除@RequestBody注释。
然后尝试以下方法:
修改LoginController代码:
@Controller
public class LoginController {@Autowiredprivate LoginService loginService;@RequestMapping(value = "/login",method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})@ResponseBodypublic Object login(UserDTO userDTO){return loginService.login(userDTO.getUsername(),userDTO.getPassword());}
}
重新试一下~~访问成功,问题解决啦