java - 即使启用 CORS,POST 也会被阻止

标签 java javascript angularjs spring-mvc cors

我根据 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 请求的 Controller 代码如下:

@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);

它无法完成请求,并且两行都在同一个 Controller 中!

这就是我在 Firebug 中看到的情况,由于某种原因,当我执行 POST 时,Firebug 只显示一个 OPTIONS 请求,之后就没有 POST 了。 enter image description here

谢谢。

最佳答案

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");

关于java - 即使启用 CORS,POST 也会被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28855198/

相关文章:

java - 如何更改外部类?

Java 实例化新的 Map.Entry-array

html - Ionic + AngularJs 自定义 css 转换不起作用

html - 单击外部时如何隐藏 uib-popover

java - 来自其他类的@Autowired @Bean

php - 使用 javascript/ajax 通过 anchor 运行 php 文件?

javascript - AngularJS:带有过滤器和 ng-change 的 ng-options

javascript - JS中如何判断null并据此实现逻辑?

javascript - AngularJS 在屏幕之间发送值

java - 在我的简单代码中找不到逻辑错误