8

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');
   }
});
bryanmac
  • 38,941
  • 11
  • 91
  • 99
ciochPep
  • 2,472
  • 4
  • 26
  • 30

4 Answers4

9

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

bryanmac
  • 38,941
  • 11
  • 91
  • 99
1

Is this method suitable for your needs?

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

Of course you need to use express/connect static middleware to get this sample work:

app.use(express.static(__dirname + '/path_to_static_root'));

UPDATE:

Also you can simple stream file content to response:

var fs = require('fs');
app.post('/bla',function(req,res,next){
   //some code
   if(cond){
      var fileStream = fs.createReadStream('path_to_dir/staticFile.html');
      fileStream.on('open', function () {
          fileStream.pipe(res);
      });
   }
});
Vadim Baryshev
  • 25,689
  • 4
  • 56
  • 48
1

Sine express deprecated res.sendfile you should use res.sendFile instead.

Pay attention that sendFile expects a path relative to the current file location (not to the project's path like sendfile does). To give it the same behaviour as sendfile - just set root option pointing to the application root:

var path = require('path');
res.sendFile('./static/index.html', { root: path.dirname(require.main.filename) });

Find here the explanation concerning path.dirname(require.main.filename)

Alexander
  • 7,484
  • 4
  • 51
  • 65
0

Based on @bryanmac's answer:

app.use("/my-rewrite", (req, res, next) => {
    const indexFile = path.join(__dirname, "index.html");

    // Check if file exists
    fs.stat(indexFile, (err, stats) => {
        if (err) {
            // File does not exist or is not accessible.
            // Proceed with other middlewares. If no other
            // middleware exists, expressjs will return 404.
            next();
            return;
        }

        // Send file
        res.sendFile(indexFile);
    });
});

Since path.exists and path.existsSync don't exist anymore in Node.js v16.9.1, fs.stat is used.

squarebrackets
  • 987
  • 2
  • 12
  • 19