在 express 和 react 中用 index.html 回应

responding with index.html in express and react

我有一个 express 应用,里面有一个 create-react-app。当用户进入 root url 时,我想显示 create-react-app public 文件夹中的 index.html。这是我在 express app

中用于 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'))。看这里:https://expressjs.com/en/starter/static-files.html

如果你想使用 sendFile() 你可以这样做:

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

我正在使用路径,因为根据您启动应用程序的方式,它可能仅与相对路径中断。