Babish Shrestha
Babish Shrestha

Reputation: 2301

Node js 404 and angular url refresh conflict

I am making an Nodejs and angular js app. I had to make a page loads when someone type on url and enter it. It worked fine until I also made a script to redirect to 404 error page. Now the problem is with both script only one of the criteria works. When 404 redirection works i cannot go to the page with url typed on browser and when that works then 404 page is redirected to index. html.

Here are the two scripts that I have use.

app.use(function(req, res) {
    res.render('404', {layout: false, title: '404: File Not Found'});
});

app.use('/*', function (req, res) {
   res.sendFile(__dirname + '/public/index.html');
});

Am I doing anything wrong over here. Beside this I also have my general routes which works fine in angular app when I click it from navigation.

Upvotes: 3

Views: 1421

Answers (3)

Lane Campbell
Lane Campbell

Reputation: 61

Put this before your 404 route:

app.use('/reload/reload.js', express.static('node_modules/reload/lib/reload.js'));

Upvotes: 0

Adeel
Adeel

Reputation: 19228

The 404 route must be the last route.

Upvotes: 1

Manwal
Manwal

Reputation: 23816

Put 404 handler code at end (It must be last route)

Use your code like this:

app.use('/*', function (req, res) {
   res.sendFile(__dirname + '/public/index.html');
});

app.use(function(req, res) { //put this at end
    res.status(404);//add this line for setting 404 status
    res.render('404', {layout: false, title: '404: File Not Found'});
});

Upvotes: 5

Related Questions