1

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>
heshamelmasry99
  • 380
  • 4
  • 12
  • look into this https://stackoverflow.com/questions/43555282/react-js-application-showing-404-not-found-in-nginx-server – Kiran Kumar Nov 20 '17 at 15:29

1 Answers1

1

dont know about deployment in heroku, but i have tried deploying in public ip and got the same issue, I think its because routing is working properly in localhost but not working during deployment with nginx.

I have edited the "default" file which is in /etc/nginx/sites-available/default in my machine nginx/1.4.6 (Ubuntu)

sudo gedit /etc/nginx/sites-available/default

Inside the server you can find location, edit that and change to

server{
.......
location / {
try_files $uri /index.html;
} 
........
}

Its simple. This worked for me. Hope this will help someone. Thanks

Shinto Joseph
  • 2,809
  • 27
  • 25