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

标签 javascript node.js express

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

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 网址的代码:

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

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

即使路径是正确的(我什至尝试使用 path.join(__dirname + '/pubblica/inserisciutente.html) 并得到相同的结果),但在访问 url 时,我只是得到一个空白页面(里面甚至有 Node conde),我还设置了: app.use(express.static('/pubblica'))如果我尝试用 res.send('Some stuff') 替换 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 文档 here .

关于javascript - ExpressJs res.sendFile 在中间件之后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201859/

相关文章:

javascript - div 填充剩余空间(宽度)

javascript - 将 camunda dmn modeler 集成到 spring mvc 应用程序中与 Angular js 前端

node.js - 尚未声明 `distinct` 的值

node.js - 显示正方形的图表 js

javascript - 如何在客户端调用fetch方法从服务器端接收数组?

javascript - 使用 nodejs 保存到 localStorage

javascript - 使用 reactJs TestUtils 模拟文本输入

javascript - 我怎么知道 Firebase 查询何时结束

node.js - 使用 Node@10.9.0 导入 o​​racledb@3.0.0 时 mkdir 权限错误

node.js - 渲染 View 之前的多个 Mongoose 查询