【问题标题】:Getting Access-Control-Allow-Origin error even tho i added app.useCors (Angular, c# .net core API)即使我添加了 app.useCors (Angular, c# .net core API),也会出现 Access-Control-Allow-Origin 错误
【发布时间】:2018-11-12 20:53:35
【问题描述】:

即使我在启动类中添加了 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();

    }

}

【问题讨论】:

  • 我使用 API .net core
  • 那你为什么要在其中添加 MVC @Aleksandar ?
  • 你能通过邮递员达到你的 api 行动吗?如果你不能问题来自你的 mvc 路由,你应该在你的问题中粘贴更多代码,顺便说一下我在回答中发布了一个技巧(代理)。

标签: c# .net angular api asp.net-core-webapi


【解决方案1】:

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

此解决方案的优点是:

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

为了使用代理

  1. 编辑您的package.json 中的"start" 以查看下方

    "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 中,发布/获取请求 url 而不是 localhost:56492/... 只需键入 /api/Film。

从这里阅读更多信息:Proxy Setup angular 2 cli

【讨论】:

  • 我应该在 c# api 中的 wwwroot 中还是在 angular 中创建 proxy.conf.json?
  • package.json所在目录下创建
  • 我的 api 的 url 是 localhost:56492 和 angular 项目的 localhost:4200,现在我得到了这个错误 localhost:4200/api/Film 404 (Not Found) 和我之前得到的 HttpErrorResponse 错误。
  • "/api": { 更改为 "/api/*": { 和测试,我编辑了我的帖子
  • 仍然得到localhost:4200/api/Film 404 (Not Found) 和 HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "localhost:4200/api/Film", ok: false, …}
猜你喜欢
  • 2019-09-20
  • 2021-01-07
  • 2018-11-10
  • 2022-11-27
  • 2017-06-15
  • 1970-01-01
  • 2020-03-06
  • 1970-01-01
  • 2017-10-29
相关资源
最近更新 更多