简体   繁体   中英

Cookie in a MERN app is not getting set up in the browser

I am having trouble seeing the request cookies in the chrome developer tools of my front end domain. If I make a login request the session cookie is not set up in the browser. However, if I make a login request, reload the back end domain and go back to the front end domain I will see the cookie. I am not experienced working with NodeJs and I don't know if this is the expected behavior or if I should see the cookie getting set up in the front end domain after I make a login request.

API front end call:

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()); 
}

back end 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);
    }));
  });
};

login route:

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);
  });

Thanks in advance.

I was also stuck in this for a lot of time.

And the answer to this is just add the proxy value to your reacts package.json . The proxy value should be the value of your backend url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM