我根据 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 了。
谢谢。
最佳答案
将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/