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

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

问题描述

我的 Heroku 应用程序使用 React 和 React Router.我使用 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天全站免登陆