Javascript 在express和react中使用index.html进行响应

Javascript 在express和react中使用index.html进行响应,javascript,reactjs,express,create-react-app,Javascript,Reactjs,Express,Create React App,我有一个express应用程序,里面有一个create react应用程序。当用户转到根url时,我想显示createreact应用程序公用文件夹中的index.html。这是我在express应用程序中为index.js编写的代码 const express = require("express"); const app = express(); app.get('/',function(req,res){ }); const PORT = process.env.PORT || 50

我有一个express应用程序,里面有一个create react应用程序。当用户转到根url时,我想显示createreact应用程序公用文件夹中的index.html。这是我在express应用程序中为index.js编写的代码

const express = require("express");
const app = express();

app.get('/',function(req,res){


});

const PORT = process.env.PORT || 5000;
app.listen(PORT);
这是我的项目目录


您需要这一行:
app.use(express.static('public'))
。请参见此处:

如果要使用
sendFile()
可以执行以下操作:

const router = express.Router();
router.get('/', (req, res) => {
    res.sendfile(path.join(__dirname, './client/public', 'index.html'));
});
app.use('/', router);

我之所以使用路径,是因为根据你启动应用程序的方式,它可能会与相对路径中断

就这样?我应该在哪里添加它以及如何获取index.htmlf的路径现在,只需将它添加到当前的
app.get
block中即可。这就是提供index.html所需的全部内容,因为这基本上会告诉您的express应用程序“当有对基本url的get请求时,请继续并公开此目录,默认情况下,如果存在index.html文件,请使用index.html文件的内容进行响应”我想在app.get(“/”)中使用res.sendFile()方法,这很好。但是express文档中推荐的方式是
express.static
,如我的回答中的链接所示,我得到了这个错误:error:enoint:no这样的文件或目录,stat'/Users/sriram/Desktop/public/index.html'是的,我会更新答案,这是路径的使用方式,考虑到您的项目结构,现在看到更新的答案是的,这正在工作。我的标题被更改为React应用程序,但我没有得到它的主体,是因为bundle.js还是其他相关的原因。我在codit(express app)内部使用create react app,正如我从您的文件夹结构图片中看到的,您尚未构建应用程序,请确保在react app中运行
npm run build