Enable HTTP Request POST in Spring Boot
I am using Spring boot, here the maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
For the web pages I am placing the files in src/main/resources/static. There I have my html files, js libraries (angular, jquery), and css files.
I am trying to make an HTTP Request POST with Angular (I also have a GET Request that is working fine) but I get this
POST http://localhost:8080/xxxx/12/addEntry 405 (Method Not Allowed)
In the Response Headers
HTTP/1.1 405 Method Not Allowed
Server: Apache-Coyote/1.1
X-Application-Context: application
Allow: HEAD, GET
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 09 Jul 2014 13:04:05 GMT
I realize that in the Response the allow doesn't have the POST method.
The method in the controller
@RequestMapping(value = "/xxxx/{uid}/addEntry", method = RequestMethod.POST)
@ResponseBody
public String createEntry(@PathVariable String uid, @RequestBody String form) {
System.out.println(form);
return "index.html";
}
Sometimes especially during initial testing Spring's csrf - Cross Site Request Forgery - protection kicks in by default and prevents POST requests from taking place, a temporary workaround is to disable csrf. This is typically done in your Web Security Config class which extends WebSecurityConfigurerAdapter
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
}
Note: This works as on Spring boot version 2.0.0.RC1 and its best if this IS NOT be used as permanent work around
A different solution worked for me. I just needed to add the proper annotation to the controller itself, like this:
@RestController
public class EntriesController {
//your code here
}
This was a while ago, sorry for don't post the answer at that time, but I will try to explain what I suppose it had happened.
I was trying to test the ajax request with the plugin of Chrome Postman, but was not possible because I've got a CORS problem (I could not do the ajax with the POST method because the server only allowed me make a HEAD or GET requests).
In the same server I had the angular application (that was the application that had to make the POST request) and the Java API (that was the application that was expecting the POST request), so there, I hadn't a CORS problem. But it was not working because I made another mistake that was that in the post method of the angular application I was not sending the payload data on the POST.
@RequestMapping(value = "/xxxx/{uid}/addEntry", method = RequestMethod.POST)
@ResponseBody
public String createEntry(@PathVariable String uid, @RequestBody String form) {
System.out.println(form);
return "index.html";
}
I hope this make the answer more clear. Thanks for reading.
链接地址: http://www.djcxy.com/p/21458.html上一篇: 如何在SBT中解决冲突的交叉版本后缀?