首页 > 解决方案 > 将 WebApi 从 Angular 分离到两个不同的项目

问题描述

现在我默认使用 VS 中的 webApi 和 Angular 应用程序这样一个项目。我想把它分成两个项目。我从我的 StarUP 文件中删除了所有与 SPA 相关的内容。我用命令运行 Angular 部分,nmp run start它在 4200 中运行。我${environment.apiUrl}/api通过这种方式为我的 api 请求添加

async loginUser(login: Login): Promise<any> {
return this.http.post(`${environment.apiUrl}/api/${environment.apiVersion}/userAuth/login`, login).toPromise();

我在网络中看到Request URL: https://localhost:44347/api/v1.0/userAuth/login

但我有cors错误。我的标题在网络中看起来像这样。

在此处输入图像描述

当我回到一个单体项目 angular 和 webApi 并运行它时。在网络中,我的标题看起来像这样。

正如您在第一种情况下看到的那样,我没有完整的标题。我如何才能将我的 Angular 应用程序与 web api 分开运行这样一个完整的单一应用程序?谢谢

在此处输入图像描述

标签: asp.netangularasp.net-coreasp.net-web-api

解决方案


如果您作为 Asp.Net Core 或 5+ 应用程序运行,您有两种方法:

1 -在您的 Web api 上启用 CORS

当您从生产中的不同服务器提供 api 和 angular 应用程序时,这是理想的选择。
开发中,您的 URL 将是:
Angular:https://localhost:4002(您将在浏览器中使用这个
WebApi:https://localhost:44347

Statup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("Any",
            builder =>
            {
                builder
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
        });
            
        options.AddPolicy("Production",
            builder => 
            { 
                builder.WithOrigins("https://your-angular-domain.com", "https://your-other-domain.com"); 
            });
    }

    // Your other services
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseCors("Any"); // Allow any origin
    }
    else
    {
        app.UseCors("Production"); // Only allow specific origins
        app.UseHsts();
        app.UseHttpsRedirection();
    }
    // Your other middlewares....
}

2.使用Spa中间件

当您从生产环境中的同一台服务器上为您的 WebAPi 和 Angular 应用程序提供服务时,这是理想的选择。

开发中,您的 URL 将是:
Angular: https://localhost:4002
WebApi: https://localhost:44347 (您将在浏览器中使用这个
Statup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Your other middlewares....

    app.UseSpa(spa =>
    {
        if (env.IsDevelopment()) // In production your angular app and web api will already be at the same server, or you should enable CORS
        {
            spa.UseProxyToSpaDevelopmentServer("http://localhost:4001");
        }
    });
}

推荐阅读