跨域请求错误: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

  今天在学习Angular 的HttpInterceptor 拦截器时,发现添加了新的headers键值之后总是报跨域错误。后台使用的是asp.net core。

检查发现,在添加了新的header之后,每次请求之前都会先发送一个options请求,这个请求被后台拒绝了,所以导致报错。我的后台跨域代码只启用了 AllowAnyOrigin()

方法,所以拒绝了options请求。

  为什么会产生options请求呢?参考以下文章,原来是添加了header之后产生非简单请求,所以浏览器会先发送一个options请求到服务器判断一下。

跨域之由Request Method:OPTIONS初窥CORS

由于是被后台拒绝的,所以修改后台代码就可以了。有两种方法

1.修改startup里的ConfigureServices 和 Configure方法

ConfigureServices:

 1    services.AddCors(options =>
 2             {
 3 
 4                 options.AddPolicy("cors", p =>
 5                 {
 6 
 7                     p.AllowAnyOrigin();
 8                     p.AllowAnyHeader();
 9                     p.AllowAnyMethod();
10                     p.AllowCredentials();
11                 });
12             });

Configure:

 app.UseCors("cors");

2.仅修改Configure方法:

   app.UseCors(cfg =>
            {
                cfg.AllowAnyOrigin(); //对应跨域请求的地址
                cfg.AllowAnyMethod(); //对应请求方法的Method
                cfg.AllowAnyHeader(); //对应请求方法的Headers
                cfg.AllowCredentials(); //对应请求的withCredentials 值
            });

注意对于非简单请求,前三个Allow方法都是必须的。

原文地址:https://www.cnblogs.com/jidanfan/p/11177509.html