Home > Net >  How do I prevent res.sendFile('/404.html') from redirecting the current path to /404.html?
How do I prevent res.sendFile('/404.html') from redirecting the current path to /404.html?

Time:01-24

I am using express 4.x to handle an error:

try {
  // ... normal logic
} catch (error) {
  // error logic
  return res.status(404).sendFile('/404.html');
}

When the user visits a non-existed path, like https://example.com/not-exist

I want the user to stay on that path /not-exist.

But it's not happening. Instead, the browser redirects me to /404.html, so what's in the address bar is: https://example.com/404.html

Is there any way to prevent this from happening?

CodePudding user response:

You must specify the root when calling sendFile. This code works for me:

try {
  // ... normal logic
} catch (error) {
  // error logic
  return res.status(404).sendFile(process.cwd() '/404.html');
}

However, if you want a shorter but deprecated approach, you can use sendfile.

try {
  // ... normal logic
} catch (error) {
  // error logic
  return res.status(404).sendfile('./404.html');
}

The difference between the non-deprecated and deprecated approach is the capitalisation of file. I recommend you only use sendFile.

CodePudding user response:

Try __dirname

try {
  // ... normal logic
} catch (error) {
  // error logic
  return res.status(404).sendFile(path.join('__dirname', '404.html'));
}
  •  Tags:  
  • Related