Reactjs 使用Joi-Express验证输入并在React中使用
我试图在后端使用Redux表单、Thunk和Joi来验证表单。 我想做的是,当用户提交表单时,我想发送我的操作,调用我的API,然后如果Joi中间件发现表单有问题,在前端根据错误做出相应的反应 我遇到的问题是,我不知道如何从Joi返回的错误状态代码中访问json 以下是我在前端的调度操作:Reactjs 使用Joi-Express验证输入并在React中使用,reactjs,express,joi,Reactjs,Express,Joi,我试图在后端使用Redux表单、Thunk和Joi来验证表单。 我想做的是,当用户提交表单时,我想发送我的操作,调用我的API,然后如果Joi中间件发现表单有问题,在前端根据错误做出相应的反应 我遇到的问题是,我不知道如何从Joi返回的错误状态代码中访问json 以下是我在前端的调度操作: export const signUp = ( newUser: User ): ThunkAction<void, AppState, null, Action<string>>
export const signUp = (
newUser: User
): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
try {
const res = await axios.post("http://localhost:2000/users/signup", newUser);
} catch (error) {
console.log("THE ERROR", error)
}
};
如果我在表格中遇到问题,我会
THE ERROR Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
但是我在catch块中找不到如何访问json(“这是您的错误”)。任何帮助都将不胜感激。非常感谢。Axios错误是内部错误。响应 您可以通过以下方式访问错误:
try {
const res = await axios.post("http://localhost:2000/users/signup", newUser);
} catch (error) {
if (error.response) {
/*The request was made and the server responded with a
status code that falls out of the range of 2xx */
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/* The request was made but no response was received, `error.request`
* is an instance of XMLHttpRequest in the browser and an instance
* of http.ClientRequest in Node.js */
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log("Error", error.message);
}
}
太棒了,谢谢!作为进一步的问题,您知道如果一切正常,为什么我不能将res返回到事件处理程序吗?我可以在处理程序中记录错误,但不能在try块工作时记录res…@Raph117我不明白你的意思,但是回答评论中的另一个问题非常困难,也许你可以问一个新问题。@Raph117最好问一个新问题,这不太费时,如果答案是有用的,请考虑接受它。我一定会看你的新问题,并尽我所能地帮助。@ RAPH117我即将回答你的新问题,你为什么删除?您需要像这样返回数据:return response.data。另外,请不要忘记将此标记为答案。
try {
const res = await axios.post("http://localhost:2000/users/signup", newUser);
} catch (error) {
if (error.response) {
/*The request was made and the server responded with a
status code that falls out of the range of 2xx */
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/* The request was made but no response was received, `error.request`
* is an instance of XMLHttpRequest in the browser and an instance
* of http.ClientRequest in Node.js */
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log("Error", error.message);
}
}