Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用express提供React应用程序时,从express.static中排除index.html_Node.js_Reactjs_Express_Create React App_Server Side Rendering - Fatal编程技术网

Node.js 使用express提供React应用程序时,从express.static中排除index.html

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”)) ); 应用程序获

我正在使用Express提供一个create-react应用程序
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
移动到该处理程序下方,即可使其正常工作。但这似乎是一个简单的解决办法。谢谢