Using Node/express/React with MySQL/Sequelize
I have a branch of my create react app app here: https://github.com/geochanto/nutrient-calculator-react/commits/edit-recipe
Which I'm deploying to Heroku here: https://nameless-temple-93876.herokuapp.com/
Locally both backend (expressjs) and frontend (React Router) routes work fine. Problem: on Heroku, while backend routes do work, only the root('/') react route works. Other routes just give a blank white page instead of loading respective components:
I tried a host of things, Mars build pack is one of them, but this instead gives an nginx error.
I also tried to manually set up static.json inside the client folder like this, but it didn't help:
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
This is my current config for the 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;
Also have this in my main 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"));
});
Other relevant files:
Answering my own question. Perhaps it will help someone else down the road:
I had a bug where I was serving the index file with res.sendFile from /client/public folder. Instead, on production environment I should have served it from /client/build , like so:
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"));
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.