预检响应具有无效的 HTTP 状态代码 401 - Spring

Response for preflight has invalid HTTP status code 401 - Spring(预检响应具有无效的 HTTP 状态代码 401 - Spring)

本文介绍了预检响应具有无效的 HTTP 状态代码 401 - Spring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人.我是 Angular 2 和 Spring Framework 的新手.我正在尝试一个带有授权标头(基本身份验证)的简单获取请求.

everyone. I'm new to Angular 2 and Spring Framework. I'm trying a simple get request with an authorization header (basic auth).

我正在使用 Spring Boot (1.2.6.RELEASE),这也可能是相关的.我的 CORS 配置如下所示.

I'm using Spring Boot (1.2.6.RELEASE), which can also be relevant. My CORS configuration looks like this.

@Component
public 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

XMLHttpRequest cannot load http://localhost:8080/api/login?username=user. Response for preflight has invalid HTTP status code 401

请帮忙,我不知道我错过了什么......我已经检查了很多帖子,但无法到达那里......

Please help, i don't know what i'm missing... I checked around a lot of posts already but couldn't get there...

推荐答案

http方法为OPTIONS时避免过滤设置状态200

avoid filtering and set status 200 when http method is OPTIONS

if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
    response.setStatus(HttpServletResponse.SC_OK);
} else {
    chain.doFilter(req, res);
}

这篇关于预检响应具有无效的 HTTP 状态代码 401 - Spring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:预检响应具有无效的 HTTP 状态代码 401 - Spring

基础教程推荐