【问题标题】:how to redirect all server requests to index.html file in node.js如何将所有服务器请求重定向到 node.js 中的 index.html 文件
【发布时间】:2021-02-01 23:48:39
【问题描述】:

我从here找到了错误的解决方案

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
})

但我无法理解我在 index.html 文件中实际写入的内容

【问题讨论】:

  • index.html 应该包含渲染应用程序所需的所有 html 代码。例如:github.com/moshfeu/synced-shopping-list/blob/master/public/…(此应用由 create-react-app 创建,但也适用于常规 react 应用)
  • 我必须在后端或前端编写此代码
  • 在前端。 i am using that build static in my backend你用的怎么样?如果你把 html 文件也放在 build 中,那么你的代码应该是res.sendFile(path.join(__dirname, 'build/index.html')
  • 你提到你正在使用 React。你如何捆绑(npm run build)反应脚本?
  • 进一步我们的聊天,只是为了回顾一下(为未来的读者),OP使用react-scripts所以index.html在build文件夹下,服务器使用res.sendFile(path.join(__dirname, 'build/index.html')提供这个html文件.

标签: node.js reactjs express routes request


【解决方案1】:

感谢@Mosh Feu,这解决了我的问题,他在解决这个问题方面帮助了我很多 你可以在这个chat看到讨论

注意:在声明到 api 的路由后使用 index.html 文件

app.use("/api", indexRouter);

app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, '/build/index.html'), function (err) {
    if (err) {
      res.status(500).send(err)
    }
  })
})

【讨论】:

    猜你喜欢
    • 2013-02-15
    • 2016-05-04
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多