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

左心房为你撑大大i 提交于 2021-02-06 09:24:28

问题


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');
   }
});

回答1:


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




回答2:


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);
      });
   }
});



回答3:


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)



来源:https://stackoverflow.com/questions/14787662/expressjs-how-to-redirect-to-a-static-file-in-the-middle-of-an-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!