我正在使用React Native编写一个移动应用程序。在某些方面,我需要发送一个发布请求并获得包括错误部分在内的响应。因此,对于某些特定输入,API(我自己的)返回409并显示一条消息。返回示例:
{
"status": 409,
"message": "E-mail is already exists!"
}
在这里,我要接收该消息并显示给用户。这是我尝试过的:
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 });
});
我尝试了error.message, error.response, error, error.data
键,但是它总是显示TypeError: undefined is not an object (evaluating 'error.message')
。那么,如何从错误对象获取消息?
编辑:这是我发送请求的方式:
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"
});
};
答案 0 :(得分:0)
根据后端返回的内容,axios中的错误消息位于错误对象的response.data
中。
.catch(error => {
const errResponse = (error && error.response && error.response.data)
|| (error && error.message);
reject(errResponse);
});
答案 1 :(得分:0)
最后,我解决了这个问题。我必须更改我的请求方法以及解决错误的方法:
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);