Node + Express + Passport + Mongoose:req.user Undefined

时间:2017-10-17 07:20:46

标签: javascript node.js express mongoose passport.js

登录时,会定义req.user,但在其他路径上,req.user未定义。也许我做错了什么,我的想法用完了。

也绝不会要求绝望

server.js:

var LocalStrategy = require('passport-local').Strategy;

const User = require('./models/user');

const app = express();

mongoose.Promise = global.Promise;

const mongoDB = 'mongodb://mlab.com:21494/tester';
mongoose.connect(mongoDB, { useMongoClient: true })
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization');

  if ('OPTIONS' == req.method) {
    res.sendStatus(200);
  } else {
    next();
  }
});

app.use(logger('dev'));

app.use(compression());

//////////////////////////////////////////////////


passport.use(new LocalStrategy(
  function(username, password, done) {
    console.log('Strategy>>>>');
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

passport.use(User.createStrategy());


passport.serializeUser(function (user, done) {
  console.log('SERIALIZE', user);   //called                     
  done(null, user.id);
});

passport.deserializeUser(function (id, done) {
  console.log('DESIRIALIZE'); // not called
  User.findById(id, function (err, user) {
    console.log('USER Desirialise', user);
    done(err, user);
  });
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Session
app.use(require('express-session')({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));

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



//=====================LOGIN==================================
app.use('/', require('./routes/userRouters'));

userRouters.js:

const router = require('express').Router();
const jwt = require('jsonwebtoken');
const passport = require('passport');

const User = require('../models/user');

router.post('/signin', passport.authenticate('local'), function (req, res, next) {
  console.log('SIGN IN');
  const { user } = req
  const token = jwt.sign({ username: user.username, email: user.email, _id: user._id }, 'RESTFULAPIs')
  console.log('REQ USER>>', req.user); // defined
  console.log('SESION', req.session.cookie); // passport defined
  res.json({
    user: {
      user: user.username,
      email: user.email,
      created: user.created
    },
    token: token
  });
})

router.get('/test', function (req, res) {
console.log('============================================');
  console.log('reqUSER', req.user); //undefined
  console.log('SESION', req.session.cookie); // passport undefined 
  res.json(req.user); 
});
///////////////////////////////////////////////////
router.post('/register', function (req, res, next) {
  const { username, email, password } = req.body;

  User.register(
    new User({ username, email, password }),
    req.body.password,
    (err, account) => {
      if (err) {
        res.send({
          status: 400,
          error: err.message,
          data: {
            errorName: err.name
          }
        });

        return;
      }

      passport.authenticate('local')(req, res, function () {
        console.log('REG req.user:>>>>', req.user); // defined
        res.send({ auth: true })
      });
    });
})

router.get('/logout', function (req, res) {
  console.log('============================================');
  console.log('reqUSER', req.user); //undefined
  console.log('SESION', req.session.cookie); // passport undefined
  req.logout();
  res.json({ messageSuccessful: 'Logout successful' });
  consol.log(req.user)// null
});

客户端:

 signUp(user) {
    const { cookies } = this.props;
    const date = new Date();
    date.setDate(date.getDate() + 2000)

    axios.post(`${URL}/register`, user).then((result) => {
      console.log('RESULT SIGNIN', result);

      if (result.data.error) {
        this.setState({ error: result.data.error })
      } 
        this.setState({
          message: result.data.message,
          auth: result.data.auth
        })
      }
    }
    )
  }

  signIn(user) {
    const { cookies } = this.props;
    const date = new Date();
    date.setDate(date.getDate() + 2000);
    axios.post(`${URL}/signin`, user).then((result) => {
      console.log('RESULT SIGNIN', result);
      if (result.data.error) {
        this.setState({ loginErrorMessage: result.data.error })
      } 
        this.setState({
          loginErrorMessage: '',
          modalIsOpen: false,
          auth: true
        })
      }
    }
    )
  };

请帮助,我试图更改会话的设置,但没有帮助。 我试图解决一个多星期。

P.S。通过邮递员检查,一切都在那里工作,deserializeUser被调用和req.user定义

1 个答案:

答案 0 :(得分:0)

问题出在客户的角色里。我希望这有助于某人。

不起作用:

axios.post(`${URL}/signin`, user).then((result) => {
//something
})

<强>工作:

const myInit = {
      method: 'post',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(user),
      mode: 'cors',
      credentials: "include",
    };

    fetch(`${URL}/signin`, myInit).then(res => res.json())
      .then(res => {
        console.log(res)
      });