简体   繁体   English

如何显示从 Node.js API 发送到 Next.js 的验证错误

[英]How to show validation errors sent from Node.js API to Next.js

I have created a Node.js API and am making requests to it using Next.js我创建了一个 Node.js API 并正在使用 Next.js 向它发出请求

Here is my Node.js controller.这是我的 Node.js controller。 I am using express validator for validation.我正在使用快速验证器进行验证。

If I fill in the form correctly, it works and the data is saved in mongo as expected.如果我正确填写表格,它可以工作,并且数据按预期保存在 mongo 中。 However, I want to send the validation errors back to the client when the form isn't filled in correctly.但是,当表单未正确填写时,我想将验证错误发送回客户端。 If I look in console, I can see the errors in the network tab.如果我查看控制台,我可以在网络选项卡中看到错误。

exports.register = async (req, res) => {
  // check if user exists in the database already
  const emailExists = await User.findOne({ email: req.body.email });
  if (emailExists) return res.status(400).send("Email already exists");

  // hash password
  const salt = await bcrypt.genSalt(10);
  // hash the password with a salt
  const passwordhash = await bcrypt.hash(req.body.password, salt);

  // create new user
  var user = new User({
    name: req.body.name,
    email: req.body.email,
    password: passwordhash
  });
  try {
    user = await user.save();
    res.send({ user: user._id });
  } catch {
    res.status(400).send(err);
  }
};

In Next.js, here is the code for making the http request在 Next.js 中,这里是发出 http 请求的代码

  handleSubmit = event => {
    const { name, email, password } = this.state;
    event.preventDefault();
    const user = {
      name,
      email,
      password
    };

    try {
      register(user);
    } catch (ex) {
      console.log(ex);
    }
  };

export const register = async user => {
  const data = await http.post("http://localhost:8000/api/user/register", user);
  console.log(data);
  return data;
};

In console all I see is the below.在控制台中,我看到的是以下内容。 So the console.log I am doing in the catch isn't working.所以我在 catch 中所做的 console.log 不起作用。

 POST http://localhost:8000/api/user/register 422 (Unprocessable Entity)

Uncaught (in promise) Error: Request failed with status code 422 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:59)未捕获(承诺中)错误:在 XMLHttpRequest.handleLoad (xhr.js:59) 的结算 (settle.js:17) 处的 createError (createError.js:16) 请求失败,状态码为 422

That's because the catch statement isn't being run because the function isn't throwing an exception by itself.那是因为没有运行 catch 语句,因为 function 本身没有抛出异常。 You should add the error handling inside the function like this:您应该像这样在 function 中添加错误处理:

 try {
      register(user);
    } catch (ex) {
      console.log(ex);
    }
 };

export const register = async user => {
  const data = await http.post("http://localhost:8000/api/user/register", user).catch((e) {
    throw new Error(e);
  });
  console.log(data);
  return data;
};

I managed to get it working like this:我设法让它像这样工作:

try {
  const response = await register(user);
  console.log(response);
} catch (ex) {
  if (ex.response && ex.response.status === 422) {
    const errors = ex.response.data.errors;
    this.setState({ errors });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM