后端代码
使用 @RequestBody Map<String, String> map
接受前端的参数
@RestController
@RequestMapping("/user/account/")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class LoginController {
private final LoginService loginService;
@PostMapping("token")
public Map<String, String> getToken(@RequestBody Map<String, String> map) {
String username = map.get("username");
String password = map.get("password");
return loginService.getToken(username, password);
}
}cha
前端代码 1(X)
$.ajax({
url: "http://127.0.0.1:8888/user/account/token/",
type: "post",
data: {
username: "mike",
password: "123456"
},
success(resp) {
console.log(resp);
},
error(resp) {
console.log(resp);
}
});
导致 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
异常
前端代码 2(X)
OK,我手动加上 Content-Type
行了吧?
$.ajax({
url: "http://127.0.0.1:8888/user/account/token/",
type: "post",
headers: {
'Content-Type':'application/json'
},
data: {
username: "mike",
password: "123456"
},
success(resp) {
console.log(resp);
},
error(resp) {
console.log(resp);
}
});
还是不行!
导致 org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'username': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
异常
前端代码 3(√)
加上 JSON.stringify()
才行!
$.ajax({
url: "http://127.0.0.1:8888/user/account/token/",
type: "post",
headers: {
'Content-Type':'application/json'
},
data: JSON.stringify({
username: "mike",
password: "123456"
}),
success(resp) {
console.log(resp);
},
error(resp) {
console.log(resp);
}
});
成功!
补充
如果想使用前端代码 1 的格式的话,后端使用 @RquestParam
注解接受即可。