【发布时间】:2020-06-02 03:42:56
【问题描述】:
我浪费了很多时间来解决这个问题,但现有的解决方案都不适用于我的情况。 让我解释一下我的服务器设置。 我有 2 个 docker 容器,一个用于 Angular 应用程序(nginx - url - http://localhost:8080)和 Spring Boot 应用程序(tomcat - url - http://localhost:8081)。 此应用正在使用 Oauth2 jdbcToken 身份验证进行 API 请求。
这个应用是一个简单的用户注册应用。
我可以注册一个新用户,因为注册 url 不安全并且没有传递任何授权标头。 但是一旦用户登录 CORS 问题就会出现。下面我列出了错误。
从源“http://localhost:8080”访问“http://localhost:8081/v1/api/group/find/shib”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。
让我告诉你我做了什么来解决这个问题。 在 Angular HTTP 请求中,我添加了以下标头。
'Authorization' : 'Bearer '+this.token(),
'Access-Control-Allow-Methods' : '*',
'Access-Control-Allow-Origin' : "*",
'Access-Control-Allow-Headers' : 'Content-Type, Accept, X-Requested-With, remember-me, Authorization',
"Access-Control-Expose-Headers" : "Content-Type, Accept, X-Requested-With, remember-me, Authorization"
在 Spring Boot 中,我在带有 CORSFilter 的 Rest 控制器上添加了 @CrossOrigin / @CrossOrigin("http:localhost:8080")
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
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, Accept, X-Requested-With, remember-me, Authorization");
chain.doFilter(req, res);
}
经过所有的试验和错误,我仍然得到同样的错误
【问题讨论】:
-
响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。
-
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} status: 0 statusText: "Unknown Error" url: "localhost:8081/v1/api/group/find/shib" ok: false name :“HttpErrorResponse”消息:“localhost:8081/v1/api/group/find/shib 的 Http 失败响应:0 未知错误”错误:ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", ...} proto: HttpResponseBase
-
@sideshowbarker 没有出现 HTTP 状态代码
-
运气不好。我试过了
标签: angularjs spring-boot docker spring-security cors