R
R
Renhor2019-06-21 13:49:20
Express.js
Renhor, 2019-06-21 13:49:20

How to correctly get user data by jwt token in Nuxt?

Hello! I created this route:

// /api/auth/getUserByToken
router.post(
  '/getUserByToken',
  passport.authenticate('jwt'),
  (req, res) => {
    res.json({
      username: req.user.username,
      email: req.user.email,
      id: req.user.id
    });
  }
);

I thought to dispatch it in nuxtServerInit
nuxtServerInit({ dispatch }) {
    dispatch('auth/autoSignin');
    dispatch('auth/getUserByToken');
}

AutoSign simply checks the browser's cookies and retrieves the token from there, so this is easily entered into Vuex.
getUserByToken makes a request to the above route, gets the user, commits it through mutations, but the user is not saved in the state.
setUser(state, user) {
    console.log(user); // Нужная информация пришла
    state.user = user;
    console.log(state.user); // Стейт обновился, но на клиенте не появился
  },

Why so - I roughly understood, the question is how to do it right and what would work?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Renhor, 2019-06-21
@Renhor

Added an async/await operator here - and everything started working.

async nuxtServerInit({ dispatch }) {
    dispatch('auth/autoSignin');
    await dispatch('auth/getUserByToken');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question