ciochPep ciochPep - 9 months ago 71
Node.js Question

expressjs: how to redirect to a static file in the middle of an handler?

I am using expressjs, I would like to do something like this:'/bla',function(req,res,next){
//some code

Answer Source

As Vadim pointed out, you can use res.redirect to send a redirect to the client.

If you want to return a static file without returning to the client (as your comment suggested) then one option is to simply call sendfile after constructing with __dirname. You could factor the code below into a separate server redirect method. You also may want to log out the path to ensure it's what you expect.

    filePath = __dirname + '/public/' + /* path to file here */;

    if (path.existsSync(filePath))
       res.statusCode = 404;
       res.write('404 sorry not found');

Here's the docs for reference:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download