如何在 Heroku 中将所有 url 重写为 index.html?

IT技术 reactjs heroku react-router
2021-05-20 19:17:07

我的 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

**编辑:我对快递不够熟悉,但这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'));
  })

1个回答

该 buildpack可以通过 JSON 文件进行配置

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

其中的样本路由配置看起来像它正是你想要的:

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

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