【问题标题】:Validating input with Joi - Express and using it in React使用 Joi - Express 验证输入并在 React 中使用它
【发布时间】: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(“这是你的错误”)。任何帮助将非常感激。非常感谢。

【问题讨论】:

    标签: reactjs express joi


    【解决方案1】:

    Axios 错误在 error.response 中。

    您可以像这样访问错误:

      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 没听懂你的意思,但是在cmets中回答另一个问题非常困难,也许你可以问一个新问题。
    • @Raph117 最好提出一个新问题,这不是很耗时,如果答案有帮助,请考虑接受。
    • 我一定会看看你的新问题,如果可以的话,尽量帮忙。
    • @Raph117 我正要回答你的新问题,你为什么要删除?您需要像这样返回数据:return response.data。另外请不要忘记将此标记为答案。
    猜你喜欢
    • 2018-05-22
    • 2017-02-03
    • 2021-04-15
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2020-05-11
    相关资源
    最近更新 更多