Lose cookie/session when reload page

2019-08-10 07:55发布

问题:

I have two separate applications:

  1. AngularJS client working on http://localhost:8080
  2. NodeJS API server working on http://localhost:3000

NodeJS API Server just gives json data to client (and does not give any html pages).

I store information about autentificated user in sessionStorage.

The Problem: When I login into system and reload page, I lost information about user in sessionStorage.

Here is my AngularJS auth service:

module.exports = function($http, $location, $cookies, $alert, $window) {
  $window.sessionStorage.setItem('currentUser',      JSON.stringify($cookies.get('user')));
  $cookies.remove('user');

  return {
   login: function(user) {
     return $http.post('http://localhost:3000/api/login', user).success(function(data) {
      $window.sessionStorage.setItem('currentUser', JSON.stringify(data));
      $location.path('/fillprofile');

      $alert({
        title: 'Cheers!',
        content: 'You have successfully logged in.',
        placement: 'top-right',
        type: 'success',
        duration: 3
      });
    }).error(function() {
        $alert({
          title: 'Error!',
          content: 'Invalid username or password.',
          placement: 'top-right',
          type: 'danger',
          duration: 3
        });
      });
  },
  signup: function(user) {
    return $http.post('http://localhost:3000/api/signup', user).success(function(data) {
      $location.path('/login');

      $alert({
        title: 'Congratulations!',
        content: 'Your account has been created.',
        placement: 'top-right',
        type: 'success',
        duration: 3
      });
    }).error(function(response) {
        $alert({
          title: 'Error!',
          content: response.data,
          placement: 'top-right',
          type: 'danger',
          duration: 3
        });
      });
  },
  logout: function() {
    return $http.get('http://localhost:3000/api/logout').success(function() {
      $window.sessionStorage.setItem('currentUser', null);
      $cookies.remove('user');
      $location.path('/login');

      $alert({
        content: 'You have been logged out.',
        placement: 'top-right',
        type: 'info',
        duration: 3
      });
    });
  }
};
};

NodeJS API

app.use(function(req, res, next) {
  if (req.user) {
    res.cookie('user', JSON.stringify(req.user));
  }
  next();
});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) next();
  else res.send(401);
}

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(function(username, password, done) {
  User.findOne({ username: username }, function(err, user) {
    if (err) return done(err);
    if (!user) return done(null, false);
    user.comparePassword(password, function(err, isMatch) {
      if (err) return done(err);
      if (isMatch) return done(null, user);
      return done(null, false);
    });
  });
}));

Routes

app.post('/api/login', passport.authenticate('local'), function(req, res) {
  res.cookie('user', JSON.stringify(req.user));
  res.send(req.user);
});

app.post('/api/signup', function(req, res, next) {
  var user = new User({
    username: req.body.username,
    email: req.body.email,
    password: req.body.password
  });
  user.save(function(err) {
    if (err) return next(err);
    res.send(200);
  });
});

app.get('/api/logout', function(req, res, next) {
  req.logout();
  res.send(200);
});

回答1:

I solved this problem by adding headers

res.header('Access-Control-Allow-Credentials', true);

to my NodeJS API server (CORS enable section). And also I need to send http request from client with withCredentials property.

$http({
    method: 'POST',
    url: 'http://localhost:3000/api/login',
    withCredentials: true,
    data: user
});

And as mentioned cdurth I need to remove $cookies.remove('user'); line. And finally change

$window.sessionStorage.setItem('currentUser', JSON.stringify($cookies.get('user')));

to

$window.sessionStorage.setItem('currentUser', $cookies.get('user'));


回答2:

Try removing $cookies.remove('user'); on line 3