此路线负责获取所有后续访问
router.get('/all', authorize, VisitController.getAllVisits);
authorize
是一个中间件,负责检查用户是否已登录并具有适当的角色:
module.exports.authorize = (req, res, next) => {
roles = ['super_admin']
if (typeof roles === 'string') {
roles = [roles];
}
verifyToken(req, res, next),
const role_ = req.get('Role')
if (roles.length && !roles.includes(role_)) {
return res.status(401).json({ message: 'Unauthorized' });
}
next();
}
并且当我首先通过邮递员以super_admin
角色调用此端点上的Get时,出现此错误(找不到404):Cannot GET /api/visits/all
在服务器端,我得到了:
(node:5920) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (C:\Users\jan\Desktop\hairdresser-service\service-api\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (C:\Users\jan\Desktop\hairdresser-service\service-api\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\jan\Desktop\hairdresser-service\service-api\node_modules\express\lib\response.js:267:15)
at Visit.find.then.documents (C:\Users\jan\Desktop\hairdresser-service\service-api\controllers\visitController.js:127:28)
at process._tickCallback (internal/process/next_tick.js:68:7)
getAllVisits
功能:
module.exports.getAllVisits = (req, res) => {
Visit.find().then(documents => {
return res.json({
message: 'Visits fetched successfully',
visits: documents
});
});
};
verifyToken
功能:
module.exports.verifyToken = (req, res, next) => {
const bearerHeader = req.headers['authorization']
if (typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(' ')
const bearerToken = bearer[1]
if(bearerToken == 'undefined' || bearerToken == '') {
res.json({
status: 403
})
}
req.token = bearerToken
next()
} else {
res.json({
status: 403
})
}
}
那么这是什么问题?有人说这是因为发送了很多回复,但我没有这样做。
添加用于授权和角色目的的中间件后,我无法从受保护的端点获取数据。此路由负责获取所有即将到来的访问router.get('/ all',授权,...
ERR_HTTP_HEADERS_SENT
告诉您,您两次结束请求。发生这种情况是因为在module.exports.authorize
中您正在调用verifyToken
,而忽略了它正在结束请求或在调用next
。