ciochPep ciochPep - 1 year ago 82
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:

app.post('/bla',function(req,res,next){
//some code
if(cond){
req.forward('staticFile.html');
}
});

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.sendfile(filePath);
    }
    else
    {
       res.statusCode = 404;
       res.write('404 sorry not found');
       res.end();
    }

Here's the docs for reference: http://expressjs.com/api.html#res.sendfile

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