ASP.NET Core - React: 无法将请求代理到 http://localhost:3000/,因为对代理目标的请求失败

ASP.NET Core - React: Failed to proxy the request to http://localhost:3000/, because the request to the proxy target failed

我正在使用 ASP.NET Core 和 ReactJS 开发一个网站。

在开发时,本地机器 运行 应用程序没有任何问题,但是,在服务器上尝试部署时,使用模板提供的默认 SPA 代码不起作用正确,因为该网站给我以下错误:

HttpRequestException: No connection could be made because the target machine actively refused it. (localhost:3000)

我看到如果使用 spa.UseProxyToSpaDevelopmentServer("http://localhost:xxxx/") 可以解决错误,但它不起作用。

我的Startup.cs看起来如下:

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

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        });

        //services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        //    .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddDefaultUI()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddControllersWithViews();
        services.AddRazorPages();

        // In production, the React files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "rx3-front/build";
        });

        services.Configure<StripeSettings>(Configuration.GetSection("Stripe"));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
    {
        StripeConfiguration.ApiKey = (Configuration.GetSection("Stripe")["SecretKey"]);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseCors(builder => builder
            .AllowAnyHeader()
            .AllowAnyMethod()
            .SetIsOriginAllowed((host) => true)
            .AllowCredentials()
        );

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseIdentityServer();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "rx3-front";

            if (env.IsDevelopment())
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
                //spa.UseProxyToSpaDevelopmentServer("http://localhost:3000/");
            }
        });

        //Custom method for initializing the database Roles and setting an unique Admin User
        CreateRoles(serviceProvider).GetAwaiter().GetResult();
    }
}

我认为还值得强调的是,在任何部署之前,我做了 运行 npm run build 所以它确实为相应的发布制作了捆绑包,以防万一它做了什么但又一次它除了让我头疼没有什么不同。

我可以开始解决这个问题的线索吗?

在创建一个用于比较和逐行阅读的新项目时,我偶然发现了 *.csproj file 中的一个微小变化导致了错误,其中更改 SpaRoot 标记值,最后需要一个 \的新值。

Project1.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
     <!-- Please note that at the end of ClientApp (being the name of the folder for the front-end) there's a backwards slash  -->
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
</PropertyGroup>

一个简单的错字,但谢天谢地,仅此而已。