解决报错: Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported]
$.ajax({
type:"post",
url:"/tproinfo/login",
data:{
"username":"username",
"password":"password"},
success:function (result){
console.log("返回的结果为:",result);
if(result.code == "1"){
alert("登录成功");
}else {
alert("登录失败");
}
}
})
在以上代码中添加:contentType: "application/json;charset-UTF-8",可以解决。 完整代码如下:
$.ajax({
contentType: "application/json;charset-UTF-8",
type:"post",
url:"/tproinfo/login",
data:{
"username":"username",
"password":"password"},
success:function (result){
console.log("返回的结果为:",result);
if(result.code == "1"){
alert("登录成功");
}else {
alert("登录失败");
}
}
})
在解决上述问题后,运行再次报错: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token ‘username’: was expecting (JSON String, Number, Array, Object or token ‘null’, ‘true’ or ‘false’); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token ‘username’: was expecting (JSON String, Number, Array, Object or token ‘null’, ‘true’ or ‘false’)at [Source: (PushbackInputStream); line: 1, column: 10]]
出现上述报错原因是Json中data数据格式不对,正确的Json格式为 data:'{"name":"zhangsan", "age":"18"}'
因此,最终的代码为:
$.ajax({
contentType: "application/json;charset-UTF-8",
type:"post",
url:"/tproinfo/login",
data:'{"username":"username",
"password":"password"}',
success:function (result){
console.log("返回的结果为:",result);
if(result.code == "1"){
alert("登录成功");
}else {
alert("登录失败");
}
}
})
推荐阅读
发表评论