使用 Express 服务 React 应用时从 express.static 中排除 index.html
Exclude index.html from express.static when serving React app with Express
我正在使用 Express 提供一个 create-react-app build
,并在提供之前将一些脚本标签附加到 index.html
。由于我在服务前操作 index.html
文件,我不希望我的 express.static
中间件处理 /
或 /index.html
的请求。以下是我为完成这项工作所做的努力:
app.use(
[/^\/index\.html/, /^\//],
express.static(path.join(__dirname, "../../build"))
);
app.get("/*", function (req, res) {
// logic to manipulate 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: false}
作为 express.static
的第二个参数传递,这将排除 index.html
从 build
目录发送。
app.use(express.static(path.join(__dirname, "../../build"), {index: false}));
app.get("*", (req, res) => {
// logic to manipulate index.html
res.send($.html());
});
我正在使用 Express 提供一个 create-react-app build
,并在提供之前将一些脚本标签附加到 index.html
。由于我在服务前操作 index.html
文件,我不希望我的 express.static
中间件处理 /
或 /index.html
的请求。以下是我为完成这项工作所做的努力:
app.use(
[/^\/index\.html/, /^\//],
express.static(path.join(__dirname, "../../build"))
);
app.get("/*", function (req, res) {
// logic to manipulate 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: false}
作为 express.static
的第二个参数传递,这将排除 index.html
从 build
目录发送。
app.use(express.static(path.join(__dirname, "../../build"), {index: false}));
app.get("*", (req, res) => {
// logic to manipulate index.html
res.send($.html());
});