angularjs - 如何调试 "No ' Access-Control-Allow-Origin' header 出现在请求的资源上”

标签 angularjs spring-security spring-boot angular-ui-router cors

我在浏览器控制台上显示此错误:

XMLHttpRequest cannot load http://localhost:8080/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9009' is therefore not allowed access.

我使用的环境是:

  • 后端- Spring Boot
  • 前端- Angularjs
  • 网络服务器- Grunt

在服务器上,我已经将请求和响应中的 header 定义为:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type");

        if (httpRequest.getMethod().equals("OPTIONS")) {
            httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }
}

我已经在此链接 No 'Access-Control-Allow-Origin' header is present on the requested resource 上找到了这个问题但找不到合适的解决方案。

这是浏览器网络图像:

enter image description here

最佳答案

您的服务器应该为预检/实际 CORS 请求添加正确的 CORS header 。我不建议实现您自己的过滤器,因为这是一个相当复杂的规范。

从 4.2 开始,Spring Framework 通过全局配置或过滤器支持 CORS - see this blog post for more information .

如果您使用的是 Spring Boot,版本 1.3.0(即将发布)will integrate this support .

关于angularjs - 如何调试 "No ' Access-Control-Allow-Origin' header 出现在请求的资源上”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101918/

相关文章:

javascript - ionic ios 应用程序卡在初始屏幕上 - 在模拟器中工作,而不是在 iphone 5s 设备上

java - 如何使用 Spring security 测试基于数据库的用户的 JWT 身份验证?

java - 扩展 JASIG CAS 的授权

java - 为什么 GlobalAuthenticationConfigurerAdapter.init() 不可见?

java - 禁用 Spring Boot HibernateJpaAutoConfiguration 但仍然收到相关错误

javascript - 来自服务的 $emit 或 $broadcast 事件并在一个(或多个) Controller 中监听它们

javascript - AngularJS 和 Bootstrap : ng-repeat causing list to lose formatting

javascript - 似乎无法在我的 AngularJS 应用程序中呈现 HTML

java - 使用 Spring Security OAuth2 刷新 token 为 null

java - 如何在 Spring-Boot 中使用 mockito-inline?