【问题标题】:ExpressJs res.sendFile doesn't work after middlewareExpressJs res.sendFile 在中间件之后不起作用
【发布时间】:2016-01-17 01:24:49
【问题描述】:

我正在尝试了解 JWT 以及它们如何与 Node 和 Express .js 一起使用。我有这个中间件尝试使用令牌对用户进行身份验证:

app.use(function(req, res, next) {
 if(req.headers.cookie) {
var autenticazione = req.headers.cookie.toString().substring(10)
autenticazione = autenticazione.substring(0, autenticazione.length - 3)
console.log(autenticazione)
jwt.verify(autenticazione, app.get('superSegreto'), function(err) {
  if (err) {
    res.send('authentication failed!')
  } else {
  // if authentication works!
    next() } })
   } else {
    console.log('errore')} })

这是我受保护的网址的代码:

app.get('/miao', function (req, res) {

res.sendFile(__dirname + '/pubblica/inserisciutente.html')
res.end() })

即使路径是正确的(我什至尝试使用 path.join(__dirname + '/pubblica/inserisciutente.html) 并得到相同的结果),在访问 url 时我只是得到一个空白页面(甚至节点 conde里面)我也设置了:app.use(express.static('/pubblica')) PS如果我尝试用 res.send('Some stuff') 替换 res.sendFile(..) 我可以在页面上正确查看它。我做错了什么?

【问题讨论】:

  • 请正确缩进您的代码。缩进不当的代码很难理解。

标签: javascript node.js express


【解决方案1】:

res.sendFile() 是异步的,如果成功就会结束自己的响应。

因此,当您在启动 res.sendFile() 后立即调用 res.end() 时,您将在代码实际发送文件之前结束响应。

你可以这样做:

app.get('/miao', function (req, res) {

    res.sendFile(__dirname + '/pubblica/inserisciutente.html', function(err) {
        if (err) {
            res.status(err.status).end();
        }
    });
});

请参阅 res.sendFile() here 的 Express 文档。

【讨论】:

  • if { } else { } else { } 是一个有效的条件吗?
  • @ChrisL - 如果 OP 正确缩进他们的代码,你会发现它实际上不是 if { } else { } else { }。最后一个else 与之前的if 配对。
【解决方案2】:

如果你想以res.end() 结束响应,那么你不能在res.sendFile() 之后提及或指定它,因为res.sendFile() 是一个异步函数,这意味着它需要一些时间来执行,同时下一条指令在您的情况下,res.end() 将执行,这就是为什么您没有看到res.sendFile 发送的任何响应

您可以访问文档以了解有关res.sendFile()visit documentation的更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 2020-02-01
    • 2020-11-27
    相关资源
    最近更新 更多