Cenobyte321
Cenobyte321

Reputation: 479

Header Access-Control-Allow-Origin:* not working properly on Spring MVC

I have a web application running on Spring MVC using RESTful web services. I'm trying to send a JSON to those web services from an HTML/Javascript file. Here's the Javascript:

$.ajax
(
{
    type: "post",
    data: JSON.stringify(data),
    contentType : "application/json",
    dataType: "json",
    url: "http://localhost/proj/service",
    success: function(data) 
    {
        callback(data);
    }
}
);

And the mapping in Spring MVC:

@RequestMapping(value = "/proj/service/", method = RequestMethod.POST)  
    public ModelAndView procRequest(@RequestBody String paramsJson, HttpServletResponse resp, WebRequest request_p){        

        resp.setStatus(HttpStatus.CREATED.value());
        resp.setHeader("Location", request_p.getContextPath() + "/proj/service");
        resp.addHeader("Access-Control-Allow-Origin", "*"); 
            //Code
}

For some reason when I delete the contentType key from the ajax request it goes through, but of course it is in an incorrect format since I expect the Javascript to send me a JSON string. But for some reason if I leave the contentType key I get the following error:

XMLHttpRequest cannot load http://localhost:8080/proj/service/. Origin http://localhost is not allowed by Access-Control-Allow-Origin. 

I don't know what could possibly be causing this error since the appropiate header is there.

Thanks.

Upvotes: 1

Views: 7626

Answers (2)

monsur
monsur

Reputation: 47907

The Content-Type header triggers a CORS preflight request. You need to modify your handler to respond to an OPTIONS request with the following headers:

resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
resp.addHeader("Access-Control-Allow-Headers", "Content-Type");

This should send the appropriate response to the preflight request, after which the browser will issue the actual request. You can learn more about preflight requests here: http://www.html5rocks.com/en/tutorials/cors/

Upvotes: 4

Cyrusmith
Cyrusmith

Reputation: 757

I do it like this:

    @RequestMapping("/listActions")
public @ResponseBody List<Action> list(HttpServletRequest request, HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");

    List<Action> actions =  new ArrayList<Action>();
    actions.add(new Action(1, "Do something fantastic"));
    actions.add(new Action(2, "Save the world"));
    actions.add(new Action(3, "Buy beer"));
    actions.add(new Action(4, "Butcher a hog"));
    return actions;
}

Upvotes: 2

Related Questions