我想限制某些路线的访问权限,我试试这个:
app.use('/app/admin', function(req, res, next){
AccessToken.findOne({ where: { id: req.cookies.Authorization}}, function(err, access_token){
if(err || !access_token) return res.json({isAdmin: false});
RoleMapping.findOne({ where: { principalId: access_token.user.id}}, function(err, role_mapping){
role_mapping.user(function(err, user){
if(err || !user) return res.json({isAdmin: false});
// trying to check this user's static role
});
if(err || !role_mapping) return res.json({isAdmin: false});
next();
});
})
});
但它最终崩溃了这个堆栈跟踪:
/Users/macbookair/node_project/microsite/node_modules/loopback-connector-mongodb/node_modules/mongodb/lib/utils.js:97
process.nextTick(function() { throw err; });
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
at ServerResponse.res.setHeader (/Users/macbookair/node_project/microsite/node_modules/loopback-explorer/node_modules/express/node_modules/connect/lib/patch.js:134:22)
at ServerResponse.header (/Users/macbookair/node_project/microsite/node_modules/loopback/node_modules/express/lib/response.js:718:10)
at ServerResponse.json (/Users/macbookair/node_project/microsite/node_modules/loopback/node_modules/express/lib/response.js:246:10)
at /Users/macbookair/node_project/microsite/server/boot/routes.js:75:34
at /Users/macbookair/node_project/microsite/node_modules/loopback-datasource-juggler/lib/dao.js:1524:62
at /Users/macbookair/node_project/microsite/node_modules/loopback-datasource-juggler/lib/dao.js:1456:9
at Object.async.each (/Users/macbookair/node_project/microsite/node_modules/loopback-datasource-juggler/node_modules/async/lib/async.js:153:20)
at allCb (/Users/macbookair/node_project/microsite/node_modules/loopback-datasource-juggler/lib/dao.js:1394:13)
at /Users/macbookair/node_project/microsite/node_modules/loopback-connector-mongodb/lib/mongodb.js:729:9
如何解决此错误或是否有其他方法限制对特定路径的访问?
答案 0 :(得分:2)
错误“错误:发送后无法设置标头。”表示您已处于Body或Finished状态,但某些函数尝试设置标题或statusCode。您似乎试图多次调用res.json
,这必须在Head中并且已完成。
你应该在找到部分正文后尝试发送标题的任何内容。