Expressjs: how to redirect to a static file in the middle of the 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'); } }); 
+4
source share
3 answers

As Vadim noted, 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 per your suggestion), one of them is to simply call sendfile after building with __dirname. You can include the code below in a separate server redirection method. You can also go out of the way to make sure 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 are the docs for reference: http://expressjs.com/api.html#res.sendfile

+4
source

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 example:

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

UPDATE:

You can also simply transfer the contents of the stream file:

 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); }); } }); 
+1
source

Sine expresses obsolete res. sendfile should use res instead. sendFile .

Note that sendFile expects a path relative to the current location of the file (not for a project path such as sendfile ). To give it the same behavior as sendfile , simply set the root parameter pointing to the root of the application:

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

Find an explanation here regarding path.dirname(require.main.filename)

0
source

All Articles