1

I have project with client and server folderds

Client: i have react redux react-router app, port: localhost:3000

Server: i have express server with express.Router() and my app bundled with webpack from client and this app avalable on '/' port: localhost:3001

When i am starting webpack-dev-server in CLIENT(port:3000) folder every route works as i wants then i am starting express server with nodemon SERVER(port:3001) and facing this problem :

Problem i faced is when i follow any Route on SERVER(port:3001) except '/' i am getting 404 error by Express. So can anyone explain me how to use react-router and express together, so all my routes from bundled app will works as they works in webpack-dev-server while development

For example we have 2 Routes:

  <Route exact path="/" component={Home} />
  <Route path="/test" component={Test} />

And we Have server.js with express app:

 app.get('*', (req,res) => 
 res.sendFile(path.join(__dirname+'/public/index.html')))

When i am getting 'localhost:3001/' Express sending index.html Then i am getting 'localhost:3001/test' And Express throw Error 404

John Rotten
  • 73
  • 1
  • 10
  • Possible duplicate of [How do I redirect into react-router from express?](https://stackoverflow.com/questions/38105453/how-do-i-redirect-into-react-router-from-express) – Agney Feb 17 '18 at 13:46
  • 1
    react router will know nothing about what's going on server side. You have to explicitly send http requests to the server via some RESTful calls ( usually via an API or service). Then you can serve data from your back end to the front end – Will Ru Feb 17 '18 at 13:48
  • @BoyWithSilverWings its only redirect i am asking how to use express.Router() with react-router – John Rotten Feb 17 '18 at 14:02
  • ` when i follow any Route on ` Can you explain what do you mean by this ? – Panther Feb 17 '18 at 14:03
  • @Panther edited – John Rotten Feb 17 '18 at 14:13
  • as in the first comments answer, you need to send index.html for all other routes(denotes by * as path) that is not handled by express. express will not know anything about react router or its routes. when u send index.html, react router will kick in the browser and render the appropiate page. you might also want to add a 404 page in react. – Panther Feb 18 '18 at 13:44
  • @Panther look at my server.js file i am sending index.html for everything – John Rotten Feb 18 '18 at 14:23
  • since express is clearly throwing 404.. your express is not sending the index.html.. so u have to make sure expreess is sending index.html as response.. – Panther Feb 18 '18 at 16:48

1 Answers1

0

add this to your Nginx app config:

location /{
...
try_files $uri %uri/ /index.html
}
Ashish Kirodian
  • 816
  • 7
  • 13