未在浏览器中设置MERN应用中的Cookie

时间:2019-01-28 20:14:22

标签: node.js reactjs cookies passport.js express-session

我无法在前端域的chrome开发人员工具中看到请求cookie。如果我发出登录请求,则不会在浏览器中设置会话cookie。但是,如果我发出登录请求,请重新加载后端域并返回到前端域,我将看到cookie。我没有使用NodeJ的经验,我不知道这是否是预期的行为,或者在发出登录请求后是否应该在前端域中设置cookie。

API前端调用:

export function loginUser(User) {
    return fetch(LOGIN_URL, {
        method: 'POST',     
        headers: {
            'content-type': 'application/json',
        },
        xhrFields: {
            withCredentials: true
        },
        body: JSON.stringify(User)
    }).then(res => res.json()); 
}

后端app.js:

const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors');
const passport = require('passport');
const session = require('express-session');
require('dotenv').config();
const middlewares = require('./middlewares');
const api = require('./api');

const app = express();


app.use(morgan('dev'));
app.use(helmet());
app.use(express.json());
app.use(cors());
require('./config/passport')(passport);
app.use(session({
  "name": "sessionCookie",
  "secret": "some-secret",
  "rolling": true,
  "saveUninitialized": true,
  "resave": false,
  cookie : { secure : false, httpOnly: false, maxAge : (4 * 60 * 60 * 1000) }
}));

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

passport.js:

const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const db = require('../db');

// Load User model
const Users = db.get('users');

module.exports = function(passport) {    
  passport.use(
    new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
      // Match user
      Users.findOne({
        email: email
      }).then(user => {        
        if (!user) {

          return done(null, false, { message: 'That email is not registered' });
        }

        // Match password
        bcrypt.compare(password, user.password, (err, isMatch) => {
          if (err) throw err;
          if (isMatch) {           
            return done(null, user);
          } else {
            return done(null, false, { message: 'Password incorrect' });
          }
        });
      });
    })
  );

  passport.serializeUser(function(user, done) {
    console.log('serialize u', user);
    done(null, user._id);
  });

  passport.deserializeUser(function(id, done) {
    console.log('desss', id);
    Users.findOne({_id: id}.then(function(err, user) {     
      done(err, user);
    }));
  });
};

登录路径:

router.post('/login', (req, res, next) => {
    passport.authenticate('local', function(err, user, info) {        
        if (err) { return next(err); }

        req.logIn(user, function(err) {            
            if (err) {return next(err); }

            console.log('successful log in', req.user);   **<--- successfully logs in user**
            console.log('sesion', req.session);  **<--- succesfully returns session object**
            return res.json(user);
            //   return res.redirect('/');
        });
      })(req, res, next);
  });

谢谢。

1 个答案:

答案 0 :(得分:0)

我也被困在这里很长一段时间。

答案是将代理值添加到您的反应package.json中。 代理值应为您的后端网址的值