问题描述
我创建了一个ASP.NET Core 3.1 Web App,并在另一个文件夹中使用create-react-app工具创建了react应用程序。我正在尝试连接这些应用程序,但是当我打开映射的终结点时,我只能看到只下载了index.html,找不到js文件。 我将特定路径映射到SPA,因为将来我需要再提供一个SPA。 ASP.NET Core启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllersWithViews();
services.AddSpaStaticFiles(config =>
{
config.RootPath = "../clients/game-app/build";
});
// ...
}
public void Configure(IApplicationBuilder app)
{
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
// ...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.MapWhen(c => c.Request.Path.Value.ToLower().StartsWith("/game"),client =>
{
client.UseSpa(spa =>
{
spa.Options.SourcePath = "../clients/game-app";
spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(),"../clients/game-app/build"))
};
if (_env.IsDevelopment())
spa.UseProxyToSpaDevelopmentServer("http://localhost:3000");
});
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
文件夹结构:
root
- Project.sln
- clients
- game-app
- build
- files created by create-react-app
- Project
- ...
- Startup.cs
- wwwroot/game-app/build - copy of build from game-app folder
我发誓它现在可以正常工作。我什至承诺要保存一切,因为我为此付出了很多努力。但是现在它停止工作了。我怀疑我做错了什么是我没有在提交前关闭React开发服务器。
现在它不起作用:
什么可能是根本原因?
解决方法
好吧,这是当我尝试使用某些映射路径充当React端点时
app.MapWhen(c => c.Request.Path.Value.ToLower().StartsWith("/game"),client => {...});
此端点开始充当静态文件提供程序,因此我可以毫无问题地获取index.html。但是index.html包含以下格式的js文件的链接:
/static/js/bundle.js
which leads to
localhost:4000/static/js/bundle.js
但是正确的地址是
localhost:4000/game/static/js/bundle.js
我在这里找到的解决方法:https://github.com/aspnet/Templating/issues/555
我添加到package.json:
"homepage": "http://localhost:3000/game",// webpack dev server address
它奏效了。