2015-10-18 81 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。好。謝謝。 –