节点,快速,护照:数据未添加到中间件的用户对象中

时间:2019-05-22 01:39:54

标签: express passport.js

我有一个使用Express,Node和Passport的应用程序。我需要将数据添加到中间件的用户对象中。

answer建议使用以下解决方案:

app.use(function(req, res, next) {
    if(req.user) req.user.whatever = 'you like';
    next();
});

但是,对我而言,数据并没有保留在用户对象中。

我的中间件:

app.use((req, res, next) => {
  if (req.user) {
    let location = req.body.location;
    console.log("location : ", location); // "USA"
    req.user.location = location;
    console.log("req.user : ", req.user); // does NOT include "location" in user object
    next();
  }

  else {
    next();
  }
});

在随后的路径中调用console.log也表明location键不会持续存在。

这是我的server.js文件的完整代码。有人可以帮我弄清楚为什么数据不持久吗?

const express = require('express');
const app = express();
const bodyparser = require("body-parser");
const passport = require("passport");
const session = require("express-session");

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// app.use(express.urlencoded({ extended: true }));
// app.use(express.json());

// bodyparser middleware
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());

// import passport-config file
require("./passport-config")(passport);

// express-session middleware
app.use(session({
  secret: process.env.SECRET,
  resave: false,
  saveUninitialized: false
}));

// passport middleware
app.use(passport.initialize());
app.use(passport.session());

app.use((req, res, next) => {
  if (req.user) {
    let location = req.body.location;
    console.log("location : ", location); // "USA"
    req.user.location = location;
    console.log("req.user : ", req.user); // does NOT include "location" in user object
    next();
  }

  else {
    next();
  }
});

const routes = require('./routes.js');
routes(app);

// listen for requests :)
const listener = app.listen(process.env.PORT, () => {
  console.log('Your app is listening on port ' + listener.address().port);
});

0 个答案:

没有答案