即使我添加了 app.useCors(Angular,c# .net core API),仍然出现 Access-Control-Allow-Origin 错误

问题描述 投票:0回答:1

即使我在启动类中添加了

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

我的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# angular .net-core asp.net-core-webapi
1个回答
0
投票

您可以在客户端中使用代理并将客户端的来源更改为您想要的任何内容。

该解决方案的优点是:

  1. 您不需要在后端定义 CORS(提高安全性)
  2. 您无需担心您的客户端,只需通过 npm start 运行您的项目,一旦您想要发布您的应用程序,您就可以运行 ng build 命令,并且代理将被忽略环境。

对于使用代理

  1. 编辑

    "start"
    package.json
    以查看下面

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

  2. 在项目的根目录中创建一个名为

    proxy.conf.json
    的新文件,并在其中定义您的代理,如下所示

    {
      "/api/*": {
        "target": "http://localhost:56492",
        "secure": "false"
      }
    }
    
  3. 重要的是你使用

    npm start
    而不是
    ng serve

现在在你的 service.ts 中,post/get 请求 url 而不是 localhost:56492/... 只需键入 /api/Film。

从这里阅读更多内容:代理设置 Angular 2 cli

© www.soinside.com 2019 - 2024. All rights reserved.