1.问题场景
在项目中发送ajax请求时,控制台提示如下错误信息: org.springframework.web.HttpRequestMethodNotSupportedException: Request method ‘GET’ not supported
2.异常解析
这个异常翻译过来就是http请求的方法映射异常,后面的详情信息说,该GET请求不被支持。
2.1异常原因
1.该请求路径存在,但是请求类型不为GET请求。
例如:
前端请求:
//前端ajax发送请求
$.ajax({
url: "http://localhost:8080/test",
type: "GET",
data: null,
datatype: "json",
success:function(data) {
console.log(data);
},
error:function(err){
console.log(err);
}
})
后台controller
@ResponseBody
@PostMapping("/test")
public String test(){
return "test";
}
这样子,如果当前的/test路径映射中只存在PostMapping,当我们又使用了GET请求去访问时,就会出现该异常。只需查看当前路径的请求类型,再修改ajax请求中的type属性的值即可。
2.2解决办法
修改ajax请求的type属性
//前端ajax发送请求
$.ajax({
url: "http://localhost:8080/test",
type: "POST", //因为服务器标明是POST请求
data: null,
datatype: "json",
success:function(data) {
console.log(data);
},
error:function(err){
console.log(err);
}
})
或者修改服务器的请求为GET请求。
@ResponseBody
@GetMapping("/test")
public String test(){
return "test";
}
3.总结
当出现org.springframework.web.HttpRequestMethodNotSupportedException: Request method ‘XXX’ not supported异常时,检查前端发送请求的路径是否与服务器映射路径上标明的请求类型对应。