POST 即使启用 CORS 也被阻止

POST Blocked even when CORS is enabled

我根据 SpringMVC 指南创建了一个 SimpleCORSFilter 以允许 CORS:

@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, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-by");
        chain.doFilter(req, res);
    }
}

POST 和 PUT 请求的控制器代码如下:

@RequestMapping(
        produces = MediaType.APPLICATION_JSON_VALUE,
        method = RequestMethod.PUT,
        value = "admin/tile/{id}"
)
public boolean saveNewTile(@PathVariable("id") String id) {
    ContextEntity contextEntity = new ContextEntity("tile", id);
    //TODO: USE CUSTOM DATABASE
    contextEntityDAO.save(contextEntity);

    return true;
}

@RequestMapping(
        produces = MediaType.APPLICATION_JSON_VALUE,
        method = RequestMethod.POST,
        value = "admin/tile/{id}"
)
public boolean updateTile(@PathVariable("id") String id, @RequestParam(required = false) ContextAttribute[] atts) {
    ContextEntity contextEntity = contextEntityDAO.findById(id);
    contextEntity.addContextAttributes(atts);

    contextEntityDAO.save(contextEntity);
    return true;
}

使用 AngularJS v1.3.14 我可以执行 GET 和 PUT 请求,但是当我尝试执行 POST 时,Firefox 通知我该请求已被阻止,因为同样-原产地政策...

这部分工作正常,例如

$scope.onTestOnlyClick = function() {
  $http.put('http://localhost:8080/admin/tile/' + tile.id)
};

然而,当我这样做时

$http.post('http://localhost:8080/admin/tile/' + tile.id, contextAtts);

无法完成请求,两条线在同一个控制器中!

这是我在 Firebug 中看到的,出于某种原因,当我执行 POST 时,Firebug 仅显示一个 OPTIONS 请求,没有 POST然后。

谢谢。

Content-Type 添加到过滤器中的 Access-Control-Allow-Headers。在我的本地测试成功。

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", "Content-Type, Origin, Cache-Control, X-Requested-With");
    response.setHeader("Access-Control-Allow-Credentials", "true");

尝试这样做-

@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, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-by");
        chain.doFilter(req, res);
        return;
     }
}