ExpressJs res.sendFile在中间件之后不起作用

skj*_*ace 0 javascript node.js express

我正在尝试了解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')} })
Run Code Online (Sandbox Code Playgroud)

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

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

res.sendFile(__dirname + '/pubblica/inserisciutente.html')
res.end() })
Run Code Online (Sandbox Code Playgroud)

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

jfr*_*d00 7

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

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

你可以这样做:

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

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

见快递文档的res.sendFile() 位置.