Reactjs ASP.NET Core 3.1为react应用程序提供静态文件:找到index.html和图标,但未找到js文件
我创建了一个ASP.NET Core 3.1 Web应用程序,并在另一个文件夹中使用创建react应用程序工具创建了react应用程序。我正在尝试连接这些应用程序,但当我打开映射的端点时,我只能看到下载了index.html,并且找不到js文件。 我将特定路径映射到SPA,因为将来我需要再提供一个SPA。 ASP.NET核心启动:Reactjs ASP.NET Core 3.1为react应用程序提供静态文件:找到index.html和图标,但未找到js文件,reactjs,asp.net-core,asp.net-core-3.1,static-files,Reactjs,Asp.net Core,Asp.net Core 3.1,Static Files,我创建了一个ASP.NET Core 3.1 Web应用程序,并在另一个文件夹中使用创建react应用程序工具创建了react应用程序。我正在尝试连接这些应用程序,但当我打开映射的端点时,我只能看到下载了index.html,并且找不到js文件。 我将特定路径映射到SPA,因为将来我需要再提供一个SPA。 ASP.NET核心启动: public void ConfigureServices(IServiceCollection services) {
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-dev服务器
现在它不起作用了:
什么是根本原因?好的,问题是当我试图使用某个映射路径作为反应端点时:
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
我在这里找到的解决方法:
我在package.json中添加了:
"homepage": "http://localhost:3000/game", // webpack dev server address
它成功了