-1

i am serving my Angular 7 project at nodejs server , on page refresh i get error Cannot GET /profile for example .

i have read that i need to add this code to allow server to load routs on refresh , and it worked but another issue showed up that my node Post or Get rquests stoped working because any route will always redirect to my main domain for example www.domain.com/api/profile will redirect to www.domain.com and the request function will not fire . any idea what to do?

note: if i remove the below code , request will work but refresh issue will show up .

 app.get('*', function (req, res){
   res.sendFile(path.join(__dirname+'/build/dist/index.html'));
 });
  • Does this answer help you? https://stackoverflow.com/a/26638143/10747134 –  Jan 20 '19 at 21:02
  • 1
    Yessss it worked !! thanks , post as answer please – Ahmed Khalaf Jan 20 '19 at 21:05
  • Actually, I'm not sure if I should post that as an answer, or if this should be called a duplicate- Sorry still new to how SO works with this. –  Jan 20 '19 at 21:07
  • Possible duplicate of [Node + Express with static HTML. How to route all requests to index.html?](https://stackoverflow.com/questions/26349497/node-express-with-static-html-how-to-route-all-requests-to-index-html) –  Jan 20 '19 at 21:08
  • haha its ok , my issue was , i was calling the code above before my Get request thats why it was not working , now after adding it after all my ReseAPI requests it works fine . thanks – Ahmed Khalaf Jan 20 '19 at 21:08
  • No problem- happy coding! –  Jan 20 '19 at 21:09
  • This code should be below your node route code. For eg. router.get/use('api') should be above this router.get('*') code. – Ram Budha Jan 20 '19 at 21:09

1 Answers1

3

Solved after adding this code after all my route requests ( GET , POST , etc) Not Before.

// other routes defined before catch-all 
server.get('/some-route', (req, res) => {
  res.send('ok')
});

// final catch-all route to index.html defined last 
server.get('*', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});