解决ajax请求(SpringMVC后台)响应415/400/405错误
后端代码
-
bean
public class user { private String username; private String password; private Integer age; //省略get set } -
SpringMVC
@RequestMapping(value = "testMethod",method = RequestMethod.POST) @ResponseBody public String getUser(@RequestBody user u){ System.out.println(u); return "success";
}
415错误
没有设置 contentType: "application/json"
-
ajax
$.ajax({ url:baseurl+"test/testMethod", type:"POST", data:JSON.stringify({ "username":"user666", "password":"a123456", "age":19 }),
success:function (res) { console.log(res); }, error:function () { console.log("网络错误"); } }) -
原因
//没有设置contentType: "application/json", //更正之后 $.ajax({ url:baseurl+"test/testMethod", type:"POST", contentType: "application/json", data:JSON.stringify({ "username":"user666", "password":"a123456", "age":19 }), success:function (res) { console.log(res); }, error:function () { console.log("网络错误"); } })
400错误
没有对传输的内容进行格式化 JSON.stringify(jsonobj)
-
ajax
$.ajax({ url:baseurl+"test/testMethod", type:"POST", contentType: "application/json", data:{ "username":"user666", "password":"a123456", "age":19 }, success:function (res) { console.log(res); }, error:function () { console.log("网络错误"); } }) -
原因
//没有对传输的数据进行转换为JSON字符串JSON.stringify(jsonobj) //更正之后
$.ajax({ url:baseurl+"test/testMethod", type:"POST", contentType: "application/json", data:JSON.stringify({ "username":"user666", "password":"a123456", "age":19 }), success:function (res) { console.log(res); }, error:function () { console.log("网络错误"); } })
405错误
通常是type 请求类型设置与后端所限制的请求不一致
-
ajax
$.ajax({ url:baseurl+"test/testMethod", type:"GET", contentType: "application/json", data:JSON.stringify({ "username":"user666", "password":"a123456", "age":19 }), success:function (res) { console.log(res); }, error:function () {
console.log("网络错误"); } }) -
原因
//请求类型与后端设置的不一致 正确应为 type:"POST" //更正之后 $.ajax({ url:baseurl+"test/testMethod", type:"POST", contentType: "application/json", data:JSON.stringify({ "username":"user666", "password":"a123456", "age":19 }), success:function (res) { console.log(res); }, error:function () { console.log("网络错误"); } })