我有一个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;
};
答案 0 :(得分:0)
原因在于访问标题
我在bootstrap文件中添加了中间件。
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if ('OPTIONS' === req.method) {
res.send(200);
}
else {
next();
}
});
答案 1 :(得分:0)
尝试使用Express Cors:https://github.com/expressjs/cors
简单用法(启用所有CORS请求)
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
跨源资源共享(CORS)是一种机制,它使用其他HTTP标头告诉浏览器让在一个源(域)上运行的Web应用程序有权从不同来源的服务器访问所选资源。 Web应用程序在请求具有与其自己的源不同的源(域,协议和端口)的资源时,会发出跨源HTTP请求。
在此处了解有关CORS的更多信息https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS