How do I rewrite all urls to index.html in Heroku?

℡╲_俬逩灬. 提交于 2020-01-25 09:17:45

问题


My Heroku app is using React with React Router. I use Switch to navigate through different components, so the URL changes as well (e.g. /room/4141). However, if I reload the page, it doesn't act like if it was a React app, but instead it searches for the mentioned .html file.

I used this Buildpack: https://github.com/mars/create-react-app-buildpack.git but it seems to do nothing in regards with pages being rewritten to index.html.

Is there a way to prevent this behaviour and rewrite all URLs to index.html?

**EDIT: I'm not familiar enough with express, but here's how the index.html is served.

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:


That buildpack can be configured via a JSON file:

You can configure different options for your static application by writing a static.json in the root folder of your application.

One of the sample routing configurations looks like it does exactly what you want:

When serving a single page app, it's useful to support wildcard URLs that serves the index.html file, while also continuing to serve JS and CSS files correctly. Route ordering allows you to do both:

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


来源:https://stackoverflow.com/questions/56131883/how-do-i-rewrite-all-urls-to-index-html-in-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!