新表达......
当我处理req.user
文件中的请求时,我可以访问app.js
。但是,即使我在routes/users.js
req.user
中对路由进行了身份验证,我在路由文件夹(特别是app.js
)中定义的路由也不会(app.use('/users', authenticate);
。正如我所提到的,我是新来的,所以我可能正在配置错误的东西。任何提示都非常感谢!如果不清楚或您需要更多信息,请告诉我。谢谢!
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var jwt = require('express-jwt');
var cors = require('cors');
var http = require('http');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var router = express.Router();
dotenv.load();
var authenticate = jwt({
secret: new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64'),
audience: process.env.AUTH0_CLIENT_ID
});
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', routes);
app.use('/users', users);
app.use('/users', authenticate);
app.use('/secured', authenticate);
app.get('/ping', function(req, res) {
res.send("All good. You don't need to be authenticated to call this");
});
app.get('/secured/ping', function(req, res) {
// req.user works here!
res.status(200).send("All good. You only get this message if you're authenticated");
});
var port = process.env.PORT || 3001;
http.createServer(app).listen(port, function (err) {
console.log('listening in http://localhost:' + port);
});
module.exports = app;
路由/ users.js
var models = require('../models');
var express = require('express');
var router = express.Router();
router.post('/', function(req, res) {
// req.user = undefined
console.log("user: " + req.user.sub)
models.User.findOrCreate({
where: {tokenId: req.user.sub},
defaults: {
name: req.body.name,
tokenId: req.user.sub,
points: 0
}
}).then(function(user) {
res.json(JSON.stringify(user));
});
});
module.exports = router;
答案 0 :(得分:1)
我认为问题在于 app.js
中以下代码的排序//some code
app.use('/users', users);
app.use('/users', authenticate);
//some code
Nodejs以顺序方式工作。因此,它将首先读取 routes / users.js 中的用户路由,然后验证功能。这样,由于后来调用了authenticate函数,因此会有未定义的req.user
。
如果您尝试在req.user
之后访问app.use('/users', authenticate)
,则不会定义(express-jwt正常工作)。
现在,如果您将代码更改为
//some code
app.use('/users', authenticate);
app.use('/users', users);
//some code
然后,它将对用户进行身份验证并将用户对象放在req.user
中,然后可以访问。
希望它适合你。如果有任何问题,请告诉我。