Sardor Sirojov
Sardor Sirojov

Reputation: 31

(Node)Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I have been learninng NodeJS and mongoDB by youtube, but unfortunately i faced with this problem, and here is my code file! thank you in advance!

db.js

const { MongoClient } = require("mongodb");

let dbConnection;

module.exports = {
  connectToDb: (cb) => {
    MongoClient.connect("mongodb://localhost:27017/bookstore")
      .then((res) => {
        dbConnection = res.db();
        return cb();
      })
      .catch((error) => {
        console.log(error);
        return cb(error);
      });
  },
  getDb: () => dbConnection,
};

index.js

const express = require("express");
const { connectToDb, getDb } = require("./db");

// init app and middleware
const app = express();

//db connection
let db;

connectToDb((xato) => {
  if (!xato) {
    app.listen(3000, () => {
      console.log("The 3000 port is installed");
    });
    db = getDb();
    return db;
  }
});

//routes
app.get("/bookstore", (req, res) => {
  let mybook = [];
  // the collection name from mongoDB
  db.collection("bookstore")
    .find()
    .sort({ author: 1 })
    .forEach((book) => mybook.push(book))
    .then(() => {
      return res.sendStatus(200).json(mybook);
    })
    .catch(() => {
      return res.sendStatus(500).send("there were an error");
    });
  // res.json({ MyWords: "I am coming from json res" });
});

it must return data from local mongodb database. But it is facing with the problem. Please give me a solution!

Upvotes: 0

Views: 108

Answers (1)

hungtran273
hungtran273

Reputation: 1347

both .sendStatus and .json will try to response to client. So the second call will result in this error.

Just use res.json(mybook) and res.send("there were an error") is enough.

In case you want to maintain status code and also send data. Use res.status(500).send("there were an error").

Upvotes: 3

Related Questions