简体   繁体   中英

Why does my node express response returns empty?

Building a registration system, when errors are made in the form, i get sent the correct errors.

But when a user with the same email tries to register 'res.json({error: 'email exists'}) ', it returns empty {}.

I'm using postman to test the responses.

What is the issue for the response to be empty?

router.post("/register", (req, res) => {
   const { name, email, password, password2 } = req.body;
   let errors = {};

   if (!name) {
    errors.name = "Name is required";
   }

   ...
   if (errors) {
      return res.json(errors);
   } else {
    User.findOne({ email: email }).then(user => {
      if (user) {
        return res.json({ email: "email already exists" });
      } else {
        ...
       ...
      ...

You are using wrong way to check empty object,

if(errors) // This will evaluate to true always once the object is initialized

true, hence empty errors object is being returned in response & its not going to check the email at all

You can use

if ( Object.keys(errors).length != 0 ) {

to check if errors object is empty

Actually problem in your if condition,

You're checking the object , you can't directly ( if(errors) ) check the object having value or not. It always go inside this if condition. If you want work correctly you have check the object containing any key or not.

You can use like this for checking the error object in if condition

if(Object.keys(errors).length > 0){
         res.json(errors);
}

可能是if (errors)返回包含 {} 的错误变量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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