Node.js 使用express提供React应用程序时,从express.static中排除index.html
我正在使用Express提供一个create-react应用程序Node.js 使用express提供React应用程序时,从express.static中排除index.html,node.js,reactjs,express,create-react-app,server-side-rendering,Node.js,Reactjs,Express,Create React App,Server Side Rendering,我正在使用Express提供一个create-react应用程序build,并在提供它之前将一些脚本标记附加到index.html。因为我在提供服务之前正在处理index.html文件,所以我不希望我的express.static中间件处理/或/index.html的请求。以下是我努力使这项工作成功的原因: app.use( [/^\/index\.html/,/^\/], express.static(path.join(\uu dirname,“../../build”)) ); 应用程序获
build
,并在提供它之前将一些脚本标记附加到index.html
。因为我在提供服务之前正在处理index.html
文件,所以我不希望我的express.static
中间件处理/
或/index.html
的请求。以下是我努力使这项工作成功的原因:
app.use(
[/^\/index\.html/,/^\/],
express.static(path.join(\uu dirname,“../../build”))
);
应用程序获取(“/*”,函数(请求,恢复){
//操作index.html的逻辑
res.send($.html());
});
但这只会给我一个空白的白色屏幕,即使原始html代码被插入,所以我假设静态中间件仍然在处理/
请求,它只是停止服务其他静态资产
如何配置此代码以使express.static停止覆盖我的/*
路由
保持路由为
/*
非常重要,因为我希望它能够处理客户端应用程序中react router中定义的所有路由。因此,我无法将express.static
中间件移动到/*
路由下,否则将覆盖所有静态资产请求。您只需在静态中间件之前为index.html
和/
添加单独的处理程序:
function serveIndex(res) {
res.send($.html());
}
app.get(["/index.html", "/"], (req, res) => {
serveIndex(res);
});
app.use(express.static(path.join(__dirname, "../../build")));
app.get("/*", (req, res) => {
serveIndex(res);
});
您只需在静态中间件之前为
index.html
和/
添加一个单独的处理程序:
function serveIndex(res) {
res.send($.html());
}
app.get(["/index.html", "/"], (req, res) => {
serveIndex(res);
});
app.use(express.static(path.join(__dirname, "../../build")));
app.get("/*", (req, res) => {
serveIndex(res);
});
实际上,我只是导入了一个包含所有react路由器路由的数组,并用它替换了
/*
。然后我只需将express.static
移动到该处理程序下方,即可使其正常工作。但这似乎是一个简单的解决办法。谢谢实际上,我只是导入了一个包含所有react路由器路由的数组,并用它替换了/*
。然后我只需将express.static
移动到该处理程序下方,即可使其正常工作。但这似乎是一个简单的解决办法。谢谢