我有一个 REST Api,当用户拥有身份验证令牌(我使用 jwt 令牌)时,所有端点都必须发送响应。当我使用邮递员测试我的代码时,一切正常,但从前面无法正常工作(会话在OPTION请求后关闭,并且在未设置请求标头承载令牌上)。
身份验证中间件
module.exports = function(req, res, next) {
const authorization = req.headers['authorization'];
console.log(authorization);
const token = authorization
? authorization.replace('Bearer ', '')
: null;
if (!token)
return res.status(403).send({ auth: false, message: 'No token provided.' });
jwt.verify(token, config.secret, function(err, decoded) {
if (err)
return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
req.userId = decoded.id;
next();
});
}
路线
const Router = require('express').Router;
//Authentication Middleware
const requireAuthentication = require('../middlewares/').Auth()
module.exports = () => {
let router = new Router();
router.use(requireAuthentication);
router.use('/accounts', require('./account')());
router.use('/projects', require('./projects')());
return router;
};