Angular2 Ng2文件上载CORS问题
我是新来尝试Angular2 Ng2文件上载CORS问题,angular,spring-boot,cors,Angular,Spring Boot,Cors,我是新来尝试angular2。我已经安装了angular2文件上传。我复制了教程中的所有代码 我完全复制开发者在那里写的东西。但我遇到这样的问题: 无法加载XMLHttpRequest。 对飞行前请求的响应未通过访问控制检查: 响应中“访问控制允许凭据”标头的值 为“”,当请求的凭据模式为“”时,该值必须为true “包括”。因此,不允许使用源“” 通道由发起的请求的凭据模式 XMLHttpRequest由withCredentials属性控制 我在我的SpringBoot @Component
angular2
。我已经安装了angular2文件上传。我复制了教程中的所有代码
我完全复制开发者在那里写的东西。但我遇到这样的问题:
无法加载XMLHttpRequest。
对飞行前请求的响应未通过访问控制检查:
响应中“访问控制允许凭据”标头的值
为“”,当请求的凭据模式为“”时,该值必须为true
“包括”。因此,不允许使用源“”
通道由发起的请求的凭据模式
XMLHttpRequest由withCredentials属性控制
我在我的SpringBoot
@Component
public class SimpleCorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept, enctype");
chain.doFilter(req, res);
}
在我添加angular2文件上传代码之前,一切都还可以。如何解决这个问题?当跨源请求发生时,它首先发送一个
HTTP选项来检查服务器是否允许跨源请求。如果您使用的是Spring安全性,请检查您是否允许,HTTP选项
在未经验证的情况下运行。如果有,添加一个这样的过滤器
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.addHeader("Access-Control-Allow-Origin", "http://localhost:4200");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
httpServletResponse.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia, Authorization");
httpServletResponse.addHeader("access-control-expose-headers", "Authorization");
if (!"OPTIONS".equals(httpServletRequest.getMethod())) {
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
首先我要添加你的代码。但它仍然是同样的错误。我只是在下面添加我的代码(在我的问题中)仍然不起作用。我不明白允许凭据的含义。您需要在websecurity配置中为HTTP选项设置“允许所有”。对于从angular应用程序发送的HTTP选项
,您应该获得200 OK
。对不起,我没有代码。但在添加SimpleCorsFilter
之前,您只需添加此权限即可。在添加过滤器之前添加.antMatchers(HttpMethod.OPTIONS).permitAll()
。