1

我有一个使用 RESTful Web 服务在 Spring MVC 上运行的 Web 应用程序。我正在尝试从 HTML/Javascript 文件向这些 Web 服务发送 JSON。这是Javascript:

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

以及 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
}

出于某种原因,当我从它通过的 ajax 请求中删除 contentType 键时,当然它的格式不正确,因为我希望 Javascript 向我发送 JSON 字符串。但是由于某种原因,如果我离开 contentType 键,我会收到以下错误:

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

我不知道什么可能导致此错误,因为适当的标头在那里。

谢谢。

4

2 回答 2

4

Content-Type头触发 CORS 预检请求。您需要修改处理程序以响应OPTIONS具有以下标头的请求:

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

这应该向预检请求发送适当的响应,之后浏览器将发出实际请求。您可以在此处了解有关预检请求的更多信息:http: //www.html5rocks.com/en/tutorials/cors/

于 2013-04-16T02:33:52.043 回答
2

我这样做:

    @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;
}
于 2013-12-24T03:57:57.477 回答