zoukankan      html  css  js  c++  java
  • 跨域请求错误: 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方法都是必须的。

  • 相关阅读:
    Sql中使用With创建多张临时表
    sql(join on 和where的执行顺序)
    什么是正则化
    ETL讲解(转)
    MySQL等 SQL语句在线练习
    Sublime text 3 --html
    Sublime text 3 搭建Python3 IDE
    地区列车经过查询
    Lasso回归算法: 坐标轴下降法与最小角回归法小结
    完全卸载VMware
  • 原文地址:https://www.cnblogs.com/jidanfan/p/11177509.html
Copyright © 2011-2022 走看看