【问题标题】:Express and React running on same port - how can I use Routing?Express 和 React 在同一端口上运行 - 我如何使用路由?
【发布时间】:2021-04-11 17:35:35
【问题描述】:

目前我通过在我的 express-server 中提供文件以静态方式提供我的 react-files:

app.use(express.static(path.join(__dirname, "..", "..", "build")));
app.get("/", function (req, res) {
  res.sendFile(path.join(__dirname, "..", "..", "build", "index.html"));
});

app.use(cors());
app.use(bodyParser.urlencoded({ limit: "10mb", extended: false }));
app.use(bodyParser.json({ limit: "10mb", extended: false }));

这很好,我可以访问我的页面、发送请求等。

现在我想实现 React-Routing,因为当我返回一次时完全离开我的站点很乏味。虽然到目前为止我非常努力,但我无法找到解决方案,因为例如我访问 localhost:3000/home 时收到错误消息,我无法使用 GET,因为它立即引用了我的快递服务器。

有什么办法可以避免这个问题吗?

【问题讨论】:

标签: node.js reactjs express react-router react-router-dom


【解决方案1】:

您也可以向 index.html 发送任何请求

这应该低于您已经定义的快速路线。

router.get(['/', '/*'], function(req, res, next) {
 res.sendFile(path.join(__dirname, "..", "..", "build", "index.html"));
});

如果你想转发快递服务器中没有的任何东西,你可以这样做

app.use(function(req, res, next) {
 res.sendFile(path.join(__dirname, "..", "..", "build", "index.html"));
});

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2017-11-04
    • 2013-12-18
    相关资源
    最近更新 更多