带有基本身份验证的Express 4投诉"发送后无法设置标头"

时间:2015-07-02 09:18:23

标签: node.js authentication express mongoose http-basic-authentication

我想授权用户尝试访问我的应用程序的编辑功能。

var basicAuth = require('basic-auth');

...

var auth = function (req, res, next) {
    function unauthorized(res) {
        res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
        return res.sendStatus(401);
    };

    var user = basicAuth(req);

    if (!user || !user.name || !user.pass) {
        return unauthorized(res);
    };

    config.administrators.forEach(function(admin){
        if (admin.email == user.name){
            if (admin.pwhash == (md5(admin.salt + user.pass))){
                req.admin = admin;
                return next();
            }
        }
    });
    return unauthorized(res);
};

router.get('/edit/', auth, function(req, res) {
    models.QuizModel.find({'author':req.admin.email}, function (err, quizes){
        res.status(200).send({'quizes': quizes});
    });
});

app.use('/api', router);

但我获得成功身份验证的所有内容都是以下错误消息:

_http_outgoing.js:335
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.header (C:\nodejs\node_modules\express\lib\response.js:718:10)
    at ServerResponse.send (C:\nodejs\node_modules\express\lib\response.js:163:12)
    at ServerResponse.json (C:\nodejs\node_modules\express\lib\response.js:249:15)
    at ServerResponse.send (C:\nodejs\node_modules\express\lib\response.js:151:21)
    at C:\nodejs\projects\demo\server.js:69:19
    at C:\nodejs\node_modules\mongoose\node_modules\kareem\index.js:109:16
    at process._tickCallback (node.js:355:11)

如果我删除模型上的猫鼬发现,并直接发送带有一些虚假信息的回复,我仍然会收到错误,我发送后无法设置标题,但应用程序赢了'崩溃,我实际上可以到达下一页。但我需要了解我的方法中的潜在问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

您正在通过return next()回调来呼叫forEach。一旦调用next(),就会调用路由器的第二个回调并发送200的状态。然后它返回到auth函数,完成迭代并调用再次发送401状态的unauthorized(res)

所以只需用forEach循环替换for即可。