1

I have a simple project based on @RestController and AngularJS. I can send GET requests from Angular to @RestController but i could not send POST request. I have an error in browser console:

XMLHttpRequest cannot load http://localhost:8080/add. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

My @RestController:

@RestController
public class AngularController {
    //@Autowired
  //  PhraseService phraseService;
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public void add(@RequestBody String str){
        logger.info("Added");
        logger.info(str);

    }

    @RequestMapping("/")
    public void angularController(){;
        logger.info("Request!");
    }
}

Here is my CORS filter:

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Content-Type", "application/json");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

My AngularJS controller:

function addController($scope, $http){
    $scope.url = 'http://localhost:8080/add';
    $scope.addPhrase = function(){
        $http.post($scope.url, {"data": $scope.value});
    }
}

And index.html:

<!doctype html>
<html ng-app>
<head>
    <title>Hello AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script src="server.js"></script>
</head>

<body>
<div ng-controller="addController">
    <form>
    <input type="text" np-model="value"/>
        <button type="button" ng-click="addPhrase()">Send!</button>
    </form>
</div>
</body>
</html>

I tried to solve this problem with header: "Content-Type": "application/json" but it gave me Bad request error.

WildCherryCandy
  • 53
  • 1
  • 1
  • 9
  • Check [this](http://stackoverflow.com/questions/12630231/how-do-cors-and-access-control-allow-headers-work) out, you probably need to add `"Content-Type"` to the `response.setHeader("Access-Control-Allow-Headers", "x-requested-with")` line. – Nikos Paraskevopoulos Mar 11 '15 at 09:57

3 Answers3

2

In Spring 4.2 and further releases, there is a first class support for CORS out-of-the-box. The details can be found on this page.

In the Spring classes annotated with RESTController, @CrossOrigin annotation can be used. Following code represents the same:

@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RestController
public class AngularController {
}

In the above code, localhost:3000 represents Angular app URL.

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
Ajitesh
  • 956
  • 10
  • 14
1

You need to add additional options in the Access-Control-Allow-Headers

Here are the options usually used:

response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Austin Greco
  • 32,997
  • 6
  • 55
  • 59
1

You could also consider using the native CORS support available in the upcoming Spring Framework 4.2 release. See this blog post for more details.

By default, it is configured to automatically accept all the headers, so it should work as soon as you enable CORS support with CrossOrigin annotation or with Java config.

Sébastien Deleuze
  • 5,950
  • 5
  • 37
  • 38