Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
}
like image 801
agusgambina Avatar asked Jul 09 '14 13:07

agusgambina


2 Answers

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

like image 125
Deepak Avatar answered Sep 22 '22 00:09

Deepak


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
}
like image 34
Nadine Avatar answered Sep 21 '22 00:09

Nadine