Skip to content
Advertisement

Not able to get the res.json() value from nodejs server

I am using react.js as frontend and nodejs for the backend. My client-side code is

export const updatePaymentDetails = (userId, token, paymentDetails) => {
  return fetch(`${API}/user/${userId}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`
    },
    body: JSON.stringify(paymentDetails)
  })
    .then(response => {
      console.log(response);
      return response.json();
    
    })
    .catch(err => console.log(err));
};

And My server-side code is

exports.updateUser = (req, res) => {
    User.findByIdAndUpdate(
        {_id: req.profile._id},
        {$set: req.body},
        {new: true, useFindAndModify: false},
        (err, user) => {
            if(err) {
                return res.status(400).json({
                    error: "You are not authorized to update this user"
                });
            }
            user.salt = undefined;
            user.encry_password = undefined;
            user.createdAt = undefined;
            user.updatedAt = undefined;
            console.log(user);
            return res.json(user);
        }
    );
};

Front-end output enter image description here

In the server-side code, you can see that I am returning the res.json. but On the client-side, I am not getting the value that I have returned from the server.

Please, can anyone help me?

Advertisement

Answer

You need to add one more then(). when you call response.json() it also returns a promise apply a then call when you return response.json()

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement