Node.js Expjs:如何在处理程序中间重定向到静态文件?

Node.js Expjs:如何在处理程序中间重定向到静态文件?,node.js,redirect,express,Node.js,Redirect,Express,我正在使用expressjs,我想做如下事情: app.post('/bla',function(req,res,next){ //some code if(cond){ req.forward('staticFile.html'); } }); 这种方法适合你的需要吗 app.post('/bla',function(req,res,next){ //some code if(cond){ res.redirect('/staticFil

我正在使用expressjs,我想做如下事情:

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

这种方法适合你的需要吗

app.post('/bla',function(req,res,next){
   //some code
   if(cond){
      res.redirect('/staticFile.html');
   }
});
当然,您需要使用express/connect
static
中间件来完成以下示例工作:

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

您还可以将简单的流文件内容发送到响应:

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指出的,您可以使用res.redirect向客户端发送重定向

如果您想返回一个静态文件而不返回到客户端(正如您的评论所建议的那样),那么一个选项就是在使用_dirname构造之后调用sendfile。您可以将下面的代码分解成一个单独的服务器重定向方法。您可能还想注销路径,以确保它符合您的期望

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

以下是供参考的文档:

Sine express不推荐的res.sendfile您应该改用res.sendfile

请注意,sendFile需要一个相对于当前文件位置的路径(而不是像sendFile那样相对于项目的路径)。要使其具有与sendfile相同的行为,只需设置指向应用程序根的root选项:

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

查找有关
path.dirname(require.main.filename)

是否可以不返回到客户端就执行此操作?express弃用的res.sendfile。改为使用res.sendFile。请在下面找到完整答案。