Search code examples
node.jsangularmongodbexpressmean-stack

How to solve HTTP header error, while status 200 ok shows in API testing using postman?


Hi All I'm new to this angular filed and im having certain issue while learning. I have been following the tutorial on youtube and was trying to as same as him just with few modification. while i did, i can see that my get API is working fine while i tested with Postman, also my post API works file with Postman, however, while i was connecting the frontend app which to backend and send data to mondoDB, but it threw an error saying code: 'ERR_HTTP_HEADERS_SENT' . Might I know this question has been asked a lot but none of the answers served my case as there were many different syntax since past

Please see the link of the documents which has detail screenshots of all my codes from image with data as well.

Please let me know what is wrong here? and why is this error coming up? Thank you all experts in advance for the help and your suggestions.

Link: to see all screenshots of codes please click the link

Thanks a lot experts, your help is really appreciated.

    const express = require ('express');
const app = express();
const bodyParser = require('body-parser');

const cors = require("cors");

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


/*
install CORS: Cross Origin Request Security
This is basically used to run two ports on same server, 
i.e Front-End: running on localhost:4200 which is using angular framework
BackEnd: localhost: running on 3000- backend api using nodejs, express
*/
app.use(bodyParser.json());
app.use(cors());

app.use ((req, res, next) =>{
  res.header("Access-Control-Allow-Orgin", "*");
  res.header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PATCH< DELETE" );
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
  
});

// app.use(express.json());
// app.get('/user', (req, res) => {
  //     person.find({})
  //     .then(user => res.send(user))
  //     .catch ((error) => console.log(error));
  // })
  app.get('/register', (req, res)=> {
      res.send("hello world");
  });


  app.post('/register', (req, res) => {
      console.log(req.body)
    // (new User ({
    //   'firstname': req.body.firstname,
    //   'lastname': req.body.lastname,
    //   'email': req.body.email,
    //   'password': req.body.password
    // }))

    // .save()
    // .then((user) => res.send(user))
    //  .catch((error) => console.log(error));
    const firstname = req.body.firstname;
    const lastname = req.body.lastname;
    const email = req.body.email;
    const password = req.body.password;
    
    
    const user = new User();
    user.firstname = firstname;
    user.lastname = lastname;
    user.email = email;
    user.password = password;
    
    user.save((err, result ) => {
      if(err){   
        console.log("There is error adding user to database");
        res.send({success: "Failed to add user to database", status: 500});
      }else {
        res.send({success: "User has been added to database", status: 200});
      } 
      
    })
    
  });
  
  
  app.listen(3000, () => console.log("Server is Connected to port 3000"));

Error Output is as below

 {
      firstName: 'kunal',
      lastName: 'patel',
      email: '[email protected]',
      password: '123454'
    }
    There is error adding user to database
    C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\mongoose\lib\helpers\promiseOrCallback.js:19
                throw error;
                ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\express\lib\response.js:267:15)
    at ServerResponse.send (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\express\lib\response.js:158:21)
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\app.js:68:20
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\mongoose\lib\model.js:4891:16
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\mongoose\lib\helpers\promiseOrCallback.js:16:11
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\mongoose\lib\model.js:4914:21
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\mongoose\lib\model.js:495:16
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\kareem\index.js:246:48
    at next (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\kareem\index.js:167:27)
    at next (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\kareem\index.js:169:9)
    at Kareem.execPost (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\kareem\index.js:217:3)   
    at _handleWrapError (C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\kareem\index.js:245:21) 
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\kareem\index.js:272:14
Emitted 'error' event on Function instance at:
\Website\Kare-app\BackEnd\node_modules\karee\Kare-app\BackEnd\node_modules\mongoose\lib\model.js:4893:13em\index.js:94:14)                         e\Kare-app\BackEnd\node_modules\mongoose\lib\helpers\promiseOrCallback.js:
    at C:\Users\tapesh.patel\Desktop\Website\Kare-app\BackEnd\node_modules\kareem\indee ...]x.js:507:38                                e\Kare-app\BackEnd\node_modules\kareem\index.js:272:14
    at processTicksAndRejections (internal/\Website\Kare-app\BackEnd\node_modules\kareem\index.js:94:14)process/task_queues.js:79:11) {            e\Kare-app\BackEnd\node_modules\kareem\index.js:507:38
  code: 'ERR_HTTP_HEADERS_SENT'            process/task_queues.js:79:11) {
}
[nodemon] app crashed - waiting for file changes before starting...                   anges before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server is Connected to port 3000
Database is connected

Solution

  • ERR_HTTP_HEADERS_SENT error occurs whenever you try to set the response header, or attempt to do something with the response, after sending the response back to the user.

    So check whether you are doing anything after sending the response back to the user. A way to avoid this is to put a return statement (see below) as this avoids the function from accidentally doing something further after you've sent the response.

    return res.send({success: "User has been added to database", status: 200});
    

    In your case, the client (Postman) gets the response correctly, but your node server is attempting to manipulate the res object again, causing the error. Check in your code if you're doing any such manipulation. Try setting that return statement.