expressjs:如何redirect到一个处理程序中的静态文件?

我正在使用expressjs,我想要做这样的事情:

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

正如Vadim所指出的那样,您可以使用res.redirect将redirect发送到客户端。

如果你想返回一个静态文件,而不返回给客户端(如你的build议),那么一个选项是简单地用__dirname构造后调用sendfile。 您可以将以下代码分解为单独的服务器redirect方法。 您也可能要注销path,以确保它是您所期望的。

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

以下是供参考的文档: http : //expressjs.com/api.html#res.sendfile

这种方法适合您的需求吗?

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

当然,您需要使用快速/连接static中间件来获取此示例工作:

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

更新:

你也可以简单的stream文件内容来响应:

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

正弦表示弃用的水库。 sendfile你应该使用res。 sendFile代替。

请注意, sendFile需要一个相对于当前文件位置的path(而不是像sendfile那样的项目path)。 为了赋予它与sendfile相同的行为 – 只需将root选项指向应用程序根目录即可:

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

在这里find关于path.dirname(require.main.filename)的解释