I have a react app and i serve it using express. It work well locally but when i deploy it to heroku i get this error 404 Not Found.
The error is when i open for example this link stand alone on a separate browser window :
http://localhost:9000/projects/5a0df094c27078039346fee2
it works very well. But if i deploy to heroku and then i try the same call i get 404. If i navigate internally i don't get 404 but this happen only if i open it on a separate window in the browser and its the heroku one . http://www.mywebsite.website/projects/5a0df05dc27078039346fedf
In my express server i have this code:
// server/app.js
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
// Setup logger
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.get('/projects/:ProjectId', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
app.get('/projects/', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('404', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
module.exports = app;
And for my react app i have this code.
<Switch>
<AppliedRoute path="/" exact component={AsyncHome} props={childProps} />
<AppliedRoute
path="/projects/:ProjectId"
exact
component={AsyncSingleProject}
props={childProps}
/>
{/* Finally, catch all unmatched routes */}
<Route component={AsyncNotFound} />
</Switch>