WTF tom
WTF tom

Reputation: 75

How to send user data object along with token to the angular front-end using node?

At the time of signup and login I want to send User's data along with JWT so that I can update current users profile data.

router.post('/signup', (req, res) => {
    let userData = req.body;
    let user = new User(userData);

    user.save((err, registeredUser) => {
        if(err) {
            console.log(err);
        }else{
            let payload =  { subject : registeredUser._id }
            let token = jwt.sign(payload, 'abcd');
            res.status(200).send({token});
        }
    });
});

How can I send registeredUser object along with token.

Upvotes: 0

Views: 293

Answers (1)

ashish.gd
ashish.gd

Reputation: 1778

Two ways :

  1. Simple and crude: res.status(200).send({token, user})
  2. Expose custom headers from your backend and send the token as part of the response. Then you can use the response body to simply send the user/resource data. res.status(200).send({user}).

Usually #2 is a better design, since the token is more like a auth/session information and can be intercepted using custom middleware/filters (eg:PassportJS) on the backend and always attached as part of the request headers from the front-end using Angular interceptors.

Express config options: headers.https://expressjs.com/en/resources/middleware/cors.html#configuration-options

Upvotes: 1

Related Questions