Home > OS >  Node Js api is failing while using POST request
Node Js api is failing while using POST request

Time:08-11

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?

CodePudding user response:

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.

CodePudding user response:

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});
}
  • Related