预检的响应具有无效的HTTP状态代码401-Spring
我正在尝试使用授权标头(基本auth)进行简单的get请求。
我正在使用Spring Boot(1.2.6.RELEASE),这也可能是相关的。我的CORS配置如下所示。
@Componentpublic class SimpleCorsFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCorsFilter.class);
public SimpleCorsFilter() {
log.info("SimpleCORSFilter init");
}
@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", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, authorization, x-auth-token");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
这是客户端的外观
this.headers.append('Authorization', 'Basic dXNlcjphZG1pbg=='); return this.http
.get(`http://localhost:8080/api/login?username=${username}`, {headers : this.headers} )
.map(response => response.json().data as any);
}
我不断得到:
XMLHttpRequest无法加载 http:// localhost:8080 / api / login?username = user。预检的响应具有无效的HTTP状态代码401
请帮助,我不知道我要缺少什么…我已经检查了很多帖子,但无法到达那里…
回答:
当http方法为OPTIONS时,避免过滤并设置状态200
if("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
以上是 预检的响应具有无效的HTTP状态代码401-Spring 的全部内容, 来源链接: utcz.com/qa/412756.html