1

I have a URL like for example 'localhost:3000/verify/a5d5sd', that I have sent to a user's email, upon clicking this link, I am using the param (a5d5sd) in the link for checking some stuff in the server and database(MongoDB) and returning a response with an object, now when the link is clicked or opened on a new tab, I only see the response from the server but not with the HTML from my Angular 2 component.

In my Angular 2 route config module, I did config a route like

  {
    path: 'verify/:id',
    component: MyComponent
  },

And on ngOnInit of this component, I am calling a service method that makes a GET http request with a URL like verify/:id the param(:id) I get it using the ActivatedRoute from the @angular/router so that I can make the request.

To handle this I was advised to have the following code for my express to use:

app.use(express.static(path.join(__dirname, 'client/dist')));

app.get('*', function(req, res) {
  res.sendFile(__dirname + '/client/dist/index.html');
})

Have even tried with:

app.all('*', function(req, res) {
  res.sendFile(__dirname + '/client/dist/index.html');
})

This code works for direct navigation(pasting URLon the search bar) and refreshes for only POST and PUT requests but not working with GET requestS that expects a response from the server side, when I directly visit a URL or refresh the page, the DOM is written with the server response but with not HTML, any assistance will be appreciated.

1 Answer 1

2

After define all routes, add the route for the index.html file

// Set your routes here
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'path/to/index.html')); //path from the root dir
});

This was work for me. Thanks

Sign up to request clarification or add additional context in comments.

6 Comments

Are you saying that it's the order of the route that is the issue?
yes. I think so. If you add the * thing above the other route definition, node will only hit on * route.
Okay I cannot really test the solution now, but did you move the * above, does it not work in your case
No of cause not. It is because nodejs find the fitted router link from top to bottom. * mean any, so it match any thing that is not match to the above routes. so the router definition that is below *, will never hit.
Okay thank you, will mark as correct after testing, I appreciate it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.