我正在春季构建一个后端 REST API,而我的朋友正在构建一个 Angular JS 前端应用程序来调用我的 API.我有一个带有键 Authorization
的令牌标头和一个可以访问的值服务,否则它会拒绝.从邮递员和 REST 客户端我能够接收 API,但是在测试时他说他在预检时收到 401 Unauthorized Error.下面是我的 doFilterInternal 方法.
I am building a backend REST API in spring and my friend is building a Angular JS front end app to call my API.I have a token header with key Authorization
and a value which gives access to the service otherwise it refuses.From Postman and REST client I am able to receive the API but when tested he says he gets 401 Unauthorized Error on preflight.Below is my doFilterInternal method.
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
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, Authorization");
}
但是当他在 Angular JS 中使用令牌调用 API 时,他得到了
But when he calls the API with the token in Angular JS he gets
所以我跟着这个答案这里 我添加了属性
So I followed this answer here and I added the property
spring.mvc.dispatch-options-request=true
在 application.properties.But stillt 他的错误似乎就像
in the application.properties.But stillt he error seems to be like
预检响应包含无效的 https 状态代码 401
感谢任何帮助.
这是避免预检错误的过滤器
Here is the filter which avoid the preflight error
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
LOG.info("Adding CORS Headers ........................");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.setHeader("Access-Control-Max-Age", "3600");
res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
if ("OPTIONS".equals(req.getMethod())) {
res.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
从帖子中找到它 Cross Origin Request Blocked Spring MVC Restful Angularjs
这篇关于如何指定 CORS 的响应标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!