2015-10-18 31 views
0

我想了解JWT以及它们如何与Node和Express .js一起工作。我有这样的中间件,试图用令牌来验证用户身份:ExpressJs res.sendFile在中间件后不工作

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

即使路径是正确的(我甚至与路径尝试。加入(__ dirname +'/pubblica/inserisciutente.html)并得到相同的结果),当访问网址我刚刚得到一个空白页(甚至节点康德里面)我也设置:app.use(express.static('/ pubblica'))PS如果我尝试用res.send('Some stuff')替换res.sendFile(..),我可以在页面上正确地查看它。我究竟做错了什么?

+0

请正确缩进您的代码。很难遵循不正确缩进的代码。 – jfriend00

回答

6

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快递文档。

+0

is if {} else {} else {}有效的条件? –

+0

@ChrisL - 如果OP会正确缩进他们的代码,你会发现它实际上不是'if else {else else {}'。最后一个'else'与之前的'if'配对。 – jfriend00

+0

Ohhhh。好。谢谢。 –