首页 > 解决方案 > 即使我添加了 app.useCors (Angular, c# .net core API),也会出现 Access-Control-Allow-Origin 错误

问题描述

即使我在我的启动类中添加了 useCors,仍然会出现 Access-Control-Allow-Origin 错误。我也在使用 Angular 5。我曾经在运行我的项目时遇到此错误,但我通过在启动时添加 cors 来修复它,但现在当我尝试从我的 Angular 项目中调用 post api 方法时得到它。 我在 chrome 中遇到的错误

我的startup.cs代码:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;

    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddMvc();

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors(builder => builder
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

    }

}

标签: c#.netangularapiasp.net-core-webapi

解决方案


You can use proxy in your client and change client's origin to whatever you want.

The advantages of this solution are :

  1. You don't need to define CORS in you'r back-end ( increase security )
  2. You don't need to be worry about your client as well as you just run your project via npm start, as soon as you want to release your application you can run ng build command and proxy will be ignored from your setting.

For using proxy

  1. edit "start" of your package.json to look below

    "start": "ng serve --proxy-config proxy.conf.json",

  2. create a new file called proxy.conf.json in the root of the project and inside of that define your proxies like below

    {
      "/api/*": {
        "target": "http://localhost:56492",
        "secure": "false"
      }
    }
    
  3. Important thing is that you use npm start instead of ng serve

Now in you'r service.ts , post/get requests url instead of localhost:56492/... just type /api/Film.

Read more from here : Proxy Setup angular 2 cli


推荐阅读