当前位置: 首页 > 知识库问答 >
问题:

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

燕烨
2023-03-14

所有人。我是Angular 2和Spring框架的新手。我正在尝试一个带有授权头(基本身份验证)的简单get请求。

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

@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);
}

帮帮我,我不知道我错过了什么...我已经查了很多帖子,但都没找到。

共有1个答案

年健
2023-03-14

http方法为选项时,避免过滤并设置状态200

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