首页 > 解决方案 > 为什么调用 API 时出现 CORS 错误

问题描述

Angular在前端使用,C#作为我的后端,当我尝试编辑字段并保存它时出现此错误:

Access to XMLHttpRequest at 'http://192.168.220.14:81/api/registry' from origin 'http://artc.tj' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

PUT http://192.168.220.14:81/api/reg polyfills-es2015.23e79c711e3c227d781f.js:1 PUT http://192.168.220.14:81/api/registry net::ERR_FAILED

错误脚本

启动.cs:

 public void ConfigureServices(IServiceCollection services)
 {
     //CORS
     services.AddCors(options =>
     {
         options.AddPolicy(MyAllowSpecificOrigins,
         builder =>
         {
             builder.WithOrigins("http://localhost",
                                 "http://localhost:4200",
                                 "http://artc.tj",
                                 "http://192.168.220.14")
                                    .AllowAnyMethod()
                                    .AllowAnyHeader()
                                    .AllowCredentials();
         });
     });
  }

标签: angularasp.net-corecors

解决方案


确保Cors()在你的Configure方法中使用。

启动.cs

public class Startup
{
   //...
   readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

   public void ConfigureServices(IServiceCollection services)
   {
      //...
         services.AddCors(options =>
         {
             options.AddPolicy(MyAllowSpecificOrigins,
             builder =>
             {
                 builder.WithOrigins("http://localhost:4200")
                     .AllowAnyHeader()
                     .AllowAnyMethod()
                     .AllowAnyOrigin();
             });
         });
      //...
   }

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
   {
      //...
      app.UseCors(MyAllowSpecificOrigins);
      //...
   }
   //...
}

PS 还要确保包含withCredentials: false在您的客户请求中httpOptions


推荐阅读