0

This problem is driving me crazy.

The purpose of this route is to create or login users, I have created new user successfully but I am having trouble sending objects as a response but all it comes is empty object.

I tried console.log() a new error that i intentionally created but it does not show up in console either

Here is the app setup

// middleware setup
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use('/', usersRoute);

my code is like this its not the full code but it shows a place where the code fails

router.post('/register', async (req, res) => {

const enteredUser = req.body;

// Validate entered user information
const { error } = validateUser(enteredUser);
if (error) return res.status(400).send(error);

try {

    // Make sure user does not exist
    const isAlreadyUser = await User.findOne({ 
        username: enteredUser.username
    });
    if (isAlreadyUser) {
        const err = new Error('already user');
        return res.status(201).send({
            isAlreadyUser,
            err
        });
    }

// Hash the password
    const salt = await bcrypt.genSalt(10);
    const hashed = await bcrypt.hash(enteredUser.password, salt);

    console.log(salt, hashed);

    // Create new model instance
    const newUser = new User({
        username: enteredUser.username,
        password: hashed,
        isCustomer: enteredUser.isCustomer
    });

    // Save new user to db
    await newUser.save();

    // generate token
    const token = newUser.genToken();

    console.log(token);

    // send token to front-end
    return res.status(200).send(token);

} catch (error) {

    return res.status(400).send(error);
}
})

the response will be like this

{
    "isAlreadyUser": {
        "isCustomer": true,
        "_id": "5fb0df0c7f3bb4069ed32615",
        "username": "Raffi2",
        "password": "$2b$10$tlHJGtax75mR4L3gG.cJhuIfy/t7IEKX4n49kIElZ41k7jZAe/2rO",
        "__v": 0
    },
    "err": {}
}

the problem happens with couple object types like Error and jsonwebtoke

can anyone help ?

Raffi
  • 699
  • 1
  • 8
  • 19

1 Answers1

1

The res.status(201).send call will return an empty object in the property err because the properties of the returned object of new Error('already user') are not enumerable and the response is JSON.stringified.

Reference:

Wasbeer
  • 389
  • 2
  • 11