express.js:如何在处理程序中间重定向到静态文件? [英] expressjs: how to redirect to a static file in the middle of an handler?

查看:51
本文介绍了express.js:如何在处理程序中间重定向到静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

正如Vadim指出的那样,您可以使用res.redirect向客户端发送重定向.

As Vadim pointed out, you can use res.redirect to send a redirect to the client.

如果要返回静态文件而不返回到客户端(如您的注释所建议),则一种选择是在使用__dirname构造后简单地调用sendfile.您可以将以下代码分解为单独的服务器重定向方法.您可能还想注销该路径,以确保它符合您的期望.

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

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

Here's the docs for reference: http://expressjs.com/api.html#res.sendfile

这篇关于express.js:如何在处理程序中间重定向到静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆