malimichael
malimichael

Reputation: 247

Can not access response data from express server in React app

In my React app, I am trying to access the error returned from this bit of server code.

  User.findByUsername(req.body.username)
    .then((foundUsername) => {
      if (foundUsername) {
        return res.status(422)
          .json({
            error: 'This username is not available.'
          });
      }

Here is the action creator on the client side

export const signupUser = ({ displayName, email, password, username }) => {
  return (dispatch) => {
    axios.post(`${API_URL}/signup`, { displayName, email, password, username })
      .then((res) => {
        dispatch({ type: AUTH_USER });
        localStorage.setItem('token', res.data.token);
        browserHistory.push('/');
      })
      .catch((res) => {
        console.log(res.data.error);
      });
  };
};

What I can't seem to figure out is that I can access res.data.token in my then case but can not get hold of res.data.error in my catch case even though I can see the response come through in the network tab on chrome.

This is what I get if I log res to the console in the catch case

Error: Request failed with status code 422 at createError (eval at 150 (bundle.e3597bf….js:39), :15:15) at settle (eval at 258 (bundle.e3597bf….js:125), :18:12) at XMLHttpRequest.handleLoad (eval at 147 (bundle.e3597bf….js:7), :77:7)

logging res in then gives me my desired object. Any help would be appreciated.

Upvotes: 0

Views: 1586

Answers (1)

Roman Schejbal
Roman Schejbal

Reputation: 626

There are two keys in the res object.

config and response

And the error message you are looking for is in res.response.data.error

Upvotes: 3

Related Questions