【问题标题】:React Router Routes Don't work when deployed to HerokuReact Router Routes 在部署到 Heroku 时不起作用
【发布时间】:2019-01-22 19:17:29
【问题描述】:

使用 Node/express/React 与 MySQL/Sequelize

我在这里有一个创建反应应用程序的分支:https://github.com/geochanto/nutrient-calculator-react/commits/edit-recipe

我在这里部署到 Heroku:https://nameless-temple-93876.herokuapp.com/

本地后端(expressjs)和前端(React Router)路由都可以正常工作。 问题: 在 Heroku 上,虽然后端路由确实有效,但只有 root('/') react 路由有效。其他路由只是给出一个空白页面而不是加载相应的组件:

我尝试了很多东西,Mars build pack 就是其中之一,但这反而给出了 nginx 错误。

我也尝试像这样在客户端文件夹中手动设置 static.json,但没有帮助:

{
"root": "build/",
"clean_urls": false,
"routes": {
    "/**": "index.html"
}

}

这是我当前对 App.js 的配置:

App.js

const App = () =>
    <Container> 
        <Router basename={process.env.PUBLIC_URL}>
            <div>
                <JumbotronComponent/>
                <NavBar />
                <Route path="/" component={Smoothie} />
                <Route exact path="/ingredients" component={Ingredients} />
                <Route exact path="/recipes" component={Recipes} />
                <Route path="/users/admin" component={Admin} />
                <Route path="/users/login" component={Login} />
                <Route path="/users/profile" component={Profile} />
                <Route path="/image" component={Imguploader} /> 
            </div>
        </Router>
    </Container>

export default App;

在我的主 server.js

中也有这个
// Serve static content for the app from the "public" directory in the application directory.
// if production env, use build folder for static files
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

// for local env, use /client/public folder
else {
  app.use(express.static(path.join(__dirname, '/client/public')));
}

// server the client index.html file for all requests
app.get("*", function(req, res) {
  res.sendFile(path.join(__dirname, "./client/public/index.html"));
});

其他相关文件:

【问题讨论】:

    标签: node.js reactjs heroku deployment react-router


    【解决方案1】:

    回答我自己的问题。也许它会帮助其他人:

    我遇到了一个错误,我使用 /client/public 文件夹中的 res.sendFile 提供索引文件。相反,在生产环境中,我应该从 /client/build 为其提供服务,如下所示:

    if (process.env.NODE_ENV === "production") {
      app.use(express.static("client/build"));
      app.get("/*", function(req, res) {
        res.sendFile(path.join(__dirname, "./client/build/index.html"));
      });
    }
    
    else {
      app.use(express.static(path.join(__dirname, '/client/public')));
      app.get("/*", function(req, res) {
        res.sendFile(path.join(__dirname, "./client/public/index.html"));
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2023-01-09
      • 2022-06-26
      • 2015-05-29
      • 2022-08-17
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2017-04-09
      相关资源
      最近更新 更多