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


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:

Answered By – bryanmac

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published