【发布时间】:2019-10-23 20:20:50
【问题描述】:
我正在尝试在后端使用 Redux Form、Thunk 和 Joi 来验证表单。 我想做的是当用户提交表单时,我想调度我的操作,它调用我的 API,然后如果 Joi 中间件发现表单有问题,根据什么在前端做出相应的反应错误是。
我遇到的问题是我不知道如何访问 Joi 发回的错误状态代码后面的 json。
这是我在前端的调度操作:
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)
}
};
然后在后端,这是我的 joi 中间件:
validateBody: (schema) => {
return (req, res, next) => {
const result = Joi.validate(req.body, schema);
if (result.error) {
return res.status(400).json({ error: "this is your error" })
}
// validated values are in req.value.body if it's there
if (!req.value) {
req.value = {};
}
req.value['body'] = result.value;
// the next allows the middleware to pass through
next();
}
},
如果我在表单中遇到问题,我会得到 p>
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(“这是你的错误”)。任何帮助将非常感激。非常感谢。
【问题讨论】: