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



我试图理解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')} })
这是我的protected url的代码:
app.get('/miao', function (req, res) {
res.sendFile(__dirname + '/pubblica/inserisciutente.html')
res.end() })

即使路径是正确的(我甚至尝试了路径。join(__dirname + '/publicica/inserisciutende .html)并得到相同的结果),当访问url时,我只是得到一个空白页面(甚至内部有节点conde)我也设置:app.use(express.static('/publicica ')) P.S.如果我尝试用res.send('一些东西')替换res.sendFile(..)我可以正确地在页面上查看它。我做错了什么?

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()的Express doc。

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

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

最新更新