0

I was just making RESTFul api in node js and mongoose and for checking whether an email existed within the mongodb database or not, i used the following code for checking that:

User.findOne({email: email }).then((userExist)=>{
        if(userExist){
            return res.status(422).json({"error": "You are already registered brother!"});
        }
    }).catch((err)=>{
        return res.json({"err": err});
    })

Now the problem is that i am constantly getting following error in console when i include an already registered email within the request in postman:

node:internal/errors:465
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (E:\py\.vscode\MERN Stack\backend\node_modules\express\lib\response.js:794:10)
    at ServerResponse.send (E:\py\.vscode\MERN Stack\backend\node_modules\express\lib\response.js:174:12)
    at ServerResponse.json (E:\py\.vscode\MERN Stack\backend\node_modules\express\lib\response.js:278:15)
    at E:\py\.vscode\MERN Stack\backend\router\auth.js:22:20
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting.

the whole code is as given below:

const express = require('express');
const Router = express.Router();
const User = require('../models/userSchema');
Router.post('/register', (req, res)=>{
    const { name, email, phone, work, password, cpassword} = req.body;
    if( !name|| !email|| !phone|| !work|| !password|| !cpassword){
        return res.status(422).json({"error": "You haven't entered required fields"});
    }
    if(password != cpassword){
        return res.status(403).json({"error": "you can't register"});
    }
    console.log(req.body);
    res.json({message: req.body});
    User.findOne({email: email }).then((userExist)=>{
        if(userExist){
            return res.status(422).json({"error": "You are already registered brother!"});
        }
    }).catch((err)=>{
        return res.json({"err": err});
    })
    const user = new User({ name:name, email:email, phone:phone, work:work, password:password, cpassword:cpassword});
    user.save().then(()=>{
        res.status(201).json({"message": "successfully stored"});
    }).catch(()=>{
        res.status(500).json({"message": "Error"});
    })
    })
module.exports = Router;

any fix?

Phil
  • 157,677
  • 23
  • 242
  • 245
haider_123
  • 39
  • 4
  • You need to move the `const user = ...` and everything afterwards into the first `.then()` callback – Phil Aug 10 '22 at 23:10
  • 1
    Does this answer your question? [ERR\_HTTP\_HEADERS\_SENT: Cannot set headers after they are sent to the client](https://stackoverflow.com/questions/52122272/err-http-headers-sent-cannot-set-headers-after-they-are-sent-to-the-client) – Phil Aug 10 '22 at 23:11

2 Answers2

0

You are sending response more than once. Just after the console.log(req.body); you are sending res.json({message: req.body}); and again condionally checking if user exists and sending response again. so remove that res.json({message: req.body}); line.

  • hey thanks! it just worked out as i am getting error code in response but the thing is that the code is still showing same error. – haider_123 Aug 11 '22 at 07:37
-1

Can you please try once with this code?

try{
    const user = await User.findOne({email});
    if(user){
        return res.status(422).json({error:"You are already registered brother!"});
    }
}catch(err){
    console.log(err);
    return res.status(500).json({error:err});
}
Drashti Kheni
  • 1,065
  • 9
  • 23