代码之家  ›  专栏  ›  技术社区  ›  geochanto

部署到Heroku时,React路由器路由不起作用

  •  0
  • geochanto  · 技术社区  · 6 年前

    对MySQL/Sequelize使用Node/express/React

    https://github.com/geochanto/nutrient-calculator-react/commits/edit-recipe

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

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

    我试过很多东西,火星建造包就是其中之一,但这反而给了 错误。

    我还尝试在客户机文件夹中手动设置static.json,但没有帮助:

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

    这是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;
    

    我也有这个 服务器.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"));
    });
    

    1 回复  |  直到 6 年前
        1
  •  2
  •   geochanto    6 年前

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

    res.sendFile文件 /客户/公众 文件夹。相反,在生产环境方面,我应该从 /客户端/生成

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