admin管理员组

文章数量:1336663

I am writing a mobile application with using React Native. At some part, I need to send a post request and get response including the error part. So, for some certain input, API(my own) returns 409 with a message. Example return:

{
    "status": 409,
    "message": "E-mail is already exists!"
}

Here, I want to take that message and show to the user. This is what I tried:

UserService.signup({ fullName, email, username, password })
  .then(response => {
    this.setState({ signUp: true });
    if (response.result) {
      Toast.show(messages.successfulSignUp, {
        backgroundColor: "green",
        duration: Toast.durations.LONG,
        position: Toast.positions.TOP
      });
      this.props.navigation.navigate("SignIn");
    } else {
    }
  })
  .catch(error => {
    Toast.show(error.message, {
      backgroundColor: "red",
      duration: Toast.durations.LONG,
      position: Toast.positions.TOP
    });
    this.setState({ signUp: false });
  });

I tried error.message, error.response, error, error.data keys, but it always says TypeError: undefined is not an object (evaluating 'error.message'). So, how can I get the message from error object?


Edit: This is how I send the request:

import { post } from "./api";

export default {
  signup: ({ fullName, email, username, password }) => {
    return post("/user/register", { fullName, email, username, password });
  }
};

export const request = config => {
  return new Promise((resolve, reject) => {
    axiosInstance
      .request({
        url: config.url,
        method: config.method || "get",
        data: config.body,
        headers: {
          "Content-Type": "application/json",
          "X-Auth-Token": store.getState().auth.token
        }
      })
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        reject(error.data);
      });
  });
};

export const post = (url, body = {}) => {
  return request({
    url,
    body,
    method: "post"
  });
};

I am writing a mobile application with using React Native. At some part, I need to send a post request and get response including the error part. So, for some certain input, API(my own) returns 409 with a message. Example return:

{
    "status": 409,
    "message": "E-mail is already exists!"
}

Here, I want to take that message and show to the user. This is what I tried:

UserService.signup({ fullName, email, username, password })
  .then(response => {
    this.setState({ signUp: true });
    if (response.result) {
      Toast.show(messages.successfulSignUp, {
        backgroundColor: "green",
        duration: Toast.durations.LONG,
        position: Toast.positions.TOP
      });
      this.props.navigation.navigate("SignIn");
    } else {
    }
  })
  .catch(error => {
    Toast.show(error.message, {
      backgroundColor: "red",
      duration: Toast.durations.LONG,
      position: Toast.positions.TOP
    });
    this.setState({ signUp: false });
  });

I tried error.message, error.response, error, error.data keys, but it always says TypeError: undefined is not an object (evaluating 'error.message'). So, how can I get the message from error object?


Edit: This is how I send the request:

import { post } from "./api";

export default {
  signup: ({ fullName, email, username, password }) => {
    return post("/user/register", { fullName, email, username, password });
  }
};

export const request = config => {
  return new Promise((resolve, reject) => {
    axiosInstance
      .request({
        url: config.url,
        method: config.method || "get",
        data: config.body,
        headers: {
          "Content-Type": "application/json",
          "X-Auth-Token": store.getState().auth.token
        }
      })
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        reject(error.data);
      });
  });
};

export const post = (url, body = {}) => {
  return request({
    url,
    body,
    method: "post"
  });
};
Share Improve this question edited Nov 2, 2019 at 18:28 SuleymanSah 17.9k6 gold badges37 silver badges59 bronze badges asked Nov 2, 2019 at 17:32 JollyRogerJollyRoger 8572 gold badges19 silver badges44 bronze badges 14
  • You can log all the keys and see if there's one you're looking for: for (key in error) console.log('key', key). If you can't find the key then you're probably not sending the correct response from your api. – Clarity Commented Nov 2, 2019 at 17:44
  • Could you try JSON.stringify(error) ? – hong developer Commented Nov 2, 2019 at 17:45
  • @Vishnudev As I said, it returns undefined – JollyRoger Commented Nov 2, 2019 at 17:58
  • There should be something wrong with your service, Is it returning a Promise @JollyRoger? – Vishnudev Krishnadas Commented Nov 2, 2019 at 17:59
  • @Clarity It did not enter the for loop. No I am sending the right response because I print what I return in my web service and there is no problem. – JollyRoger Commented Nov 2, 2019 at 18:01
 |  Show 9 more ments

2 Answers 2

Reset to default 4

Finally I solved this issue. I had to change my request method and the way I reach out to the error:

export const request = (config) => {
    return new Promise((resolve, reject) => {
        axiosInstance.request({
            url: config.url,
            method: config.method || 'get',
            data: config.body,
            headers: {
                'Content-Type': 'application/json',
                'X-Auth-Token': store.getState().auth.token,
            }
        }).then(response => {
            resolve(response.data)
        }).catch(error => {
            reject(error.response)
        })
    })
}

// This is how reach out to the error message:
console.log(error.data.message);

Depending on what the backend returns, the error message in axios is in response.data of the error object.

.catch(error => {

    const errResponse = (error && error.response && error.response.data) 
     || (error && error.message); 

    reject(errResponse);
});

本文标签: javascriptCan39t Get Error Message From Axios Response in React NativeStack Overflow