1

新表达...

req.user当我处理文件中的请求时,我可以访问app.js。但是,即使我routes/users.js在. 正如我所提到的,我是新来表达的,所以我可能配置不正确。非常感谢任何提示!如果不清楚或者您需要更多信息,请告诉我。谢谢!req.userapp.js (app.use('/users', authenticate);

应用程序.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;
4

1 回答 1

1

我认为问题在于app.js中以下代码的排序

//some code
app.use('/users', users);
app.use('/users', authenticate);
//some code

Nodejs 以顺序方式工作。因此,它将首先读取routes/users.js中的用户路由,然后进行身份验证功能。这样,之后就会req.user调用未定义的身份验证函数。

如果您尝试访问req.userafter app.use('/users', authenticate),它不会是未定义的( express-jwt 可以正常工作)。

现在,如果您将代码更改为

//some code
app.use('/users', authenticate);
app.use('/users', users);
//some code

然后,它将对用户进行身份验证并将用户对象放入req.user,之后就可以访问了。

希望对你有效。让我知道,如果有任何问题。

于 2016-03-08T07:13:11.363 回答