I made a simple create-react-app application and a node.js express server side. locally this works (server serves ui and do api) but when deploying to heroku only UI is served (any API call gets a 503 code)
App.js
// Routes
// works both locally and on heroku
app.get('/ui', (req, res) => {
res.sendFile(path.resolve(__dirname,'build','index.html'));
});
// works only locally
app.use('/users',users);
app.use('/pledge',pledge);
React router
<ThemeProvider theme={theme}>
<div>
<Router history={history}>
<div>
<Route path={'/ui/'} component={Header}/>
<Route exact={true} path='/ui/welcome' component={Welcome}/>
<Route exact={true} path="/ui/login" component={Login}/>
<Route exact={true} path="/ui/help" component={Help}/>
<Route exact={true} path="/ui/dashboard" component={DashBoard}/>
<Route exact={true} path='/ui/logout' component={Logout}/>
<Route exact={true} path='/ui/pledge' component={Pledge}/>
<Route exact={true} path='/ui/buckets' component={Bucket}/>
<Route exact={true} path='/ui/add' component={AddStuff}/>
<Route exact={true} path='/ui/motion' component={MotionInput}/>
<Route exact={true} path='/ui/status' component={Status}/>
</div>
</Router>
</div>
</ThemeProvider>
No server side rendering. example for API:
app.post('/usersAdd',(req, res) => {
let newUser = new User(req.body);
newUser.save((err) => {
if (err)
return res.send(500, {error: err});
return res.send("successfully saved");
});
});
API call
export function getUsers() {
return new Promise((resolve, reject) => {
axios.get(serverProps.server + serverProps.getUsers, {
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.then(resolve)
.catch(reject);
});
}
It's because on deploying, when going to route /users
it looks for any file named users.html and doesn't find it, so returns 503. You can fix it by redirecting all routes to index.html
by replacing your app.get
call with:
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
Have a look here . See if it works.
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.