Response for preflight has invalid HTTP status code 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
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01