Mark P Mark P - 1 year ago 88
Node.js Question

Error function not returning JSON format

I'm trying to pass a JSON error object into my code using the error function in two cases. Once in the email and password check statement and again in the if existingUser statement. I think it's just that time of the night.

const User = require('../models/user');

exports.signup = function(req, res, next) {
const email =;
const password = req.body.password;

if (!email || !password) {
return res.err("Please enter in email and password");

//See if a user with the given email exists
User.findOne({ email: email }, function(err, existingUser) {
if (err) { return next(err); }

//If a user with email does exist, return an Error
if (existingUser) {
//the status sets the status of the http code 422 means couldn't process this
return res.err( 'Email is in use' );
//If a user with email does NOT exist, create and save user record
const user = new User({
email: email,
password: password
}); {
if (err) { return next(err); }
//Respond to request indicating the user was created
res.json({ success: true });

Answer Source

At the moment you are not returning the right status code in your response, you could try this:


return res.err("Please enter in email and password");


return res.status(422).send({error: "Please enter in email and password"})

And replace:

return res.err( 'Email is in use' );


return res.status(422).send({ error: "Email is in use" });

This will send back the required status code in the http response.

Also consider only using single or double quotes in your code for consistency.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download