【问题标题】:How do I rewrite all urls to index.html in Heroku?如何在 Heroku 中将所有 url 重写为 index.html?
【发布时间】:2019-10-01 13:36:51
【问题描述】:

我的 Heroku 应用正在使用 React 和 React Router。我使用 Switch 来浏览不同的组件,因此 URL 也会发生变化(例如 /room/4141)。但是,如果我重新加载页面,它不会像 React 应用程序那样运行,而是会搜索提到的 .html 文件。

我使用了这个 Buildpack:https://github.com/mars/create-react-app-buildpack.git,但它似乎对将页面重写为 index.html 没有任何作用。

有没有办法阻止这种行为并将所有 URL 重写为 index.html

**编辑: 我对 express 不够熟悉,但这里是 index.html 的服务方式。

const express = require("../../node_modules/express");
const app = express();
const server = require("http").Server(app);
const io = module.exports.io = require('../../node_modules/socket.io/lib')(server)
const path = require("path")

app.use(express.static(path.join(__dirname, '../../build')));
if(process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../../build')));
    console.log("DEBUG HERE", __dirname, path.join(__dirname+'../../build'));
    //
    app.get('/*', (req, res) => {
      res.sendFile(path.join(__dirname+'../../build/index.html'));
    })
  }
  //build mode
  app.get('/*', (req, res) => {
    res.sendFile(path.join(__dirname+'../../public/index.html'));
  })

【问题讨论】:

  • 你可以使用带有哈希的客户端路由吗,例如https://yoursite.com/#room/4141?这应该是开箱即用的。
  • 似乎使用哈希也没有什么不同。我的页面根本没有加载。还是我做错了? <Route path="/#room/:roomCode" component={Lobby} /> *EDIT:重新加载页面也会返回Not Found

标签: reactjs heroku react-router


【解决方案1】:

那个 buildpack can be configured 通过一个 JSON 文件:

您可以通过在应用程序的根文件夹中写入static.json 来为静态应用程序配置不同的选项。

其中一个sample routing configurations 看起来完全符合您的要求:

在提供单页应用程序时,支持提供 index.html 文件的通配符 URL 非常有用,同时还能继续正确提供 JS 和 CSS 文件。路线排序允许您同时执行以下操作:

{
  "routes": {
    "/assets/*": "/assets/",
    "/**": "index.html"
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-06
    • 2014-12-17
    • 1970-01-01
    • 2014-11-29
    • 2019-02-02
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    相关资源
    最近更新 更多