如何在Heroku中将所有URL重写为index.html? [英] How do I rewrite all urls to index.html in Heroku?

查看:79
本文介绍了如何在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:

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

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:

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

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"
  }
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆