如何在Heroku中将所有URL重写为index

如何在Heroku中将所有URL重写为index

本文介绍了如何在Heroku中将所有URL重写为index.html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Heroku应用程序正在使用带有React Router的React.我使用Switch浏览不同的组件,因此URL也会更改(例如/room/4141).但是,如果我重新加载页面,它的行为就不像它是一个React应用程序,而是搜索提到的.html文件.

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.

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

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.

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

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

**我对Express不太熟悉,但是这是index.html的投放方式.

**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'));
  })

推荐答案

该buildpack 可以通过JSON文件配置:

That buildpack can be configured via a JSON file:

样本路由配置看起来完全符合您的要求:

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

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

这篇关于如何在Heroku中将所有URL重写为index.html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 20:36