skip to Main Content

I’m doing mongodb database after tutorial from NetNinja. Since I’m kinda bad with js, I’m just following his actions. I’m stuck with:

node:internal/errors:496
    ErrorCaptureStackTrace(err);
    ^
...
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I’m having only 2 files:
app.js

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

const app = express()

let db

connectToDb((err) => {
    if(!err) {
        app.listen(3000, () => {
            console.log('app listening on port 3000')
        })
        db = getDb()
    }
})

app.get('/books/books', (req, res) => {
    let books = []

    db.collection('books')
        .find()
        .sort({ author: 1 })
        .forEach(book => books.push(book))
        .then(() => {
            res.status(200).json(books)
        })
        .catch(() => {
            res.status(500).json({error : 'Could not fetch the documents'})
        })

    res.json({mssg: "welcome to the api"})
})

db.js

const { MongoClient } = require('mongodb')

let dbConnection

module.exports = {
    connectToDb: (cb) => {
        MongoClient.connect('mongodb://0.0.0.0:27017/bookstore')
            .then((client) => {
                dbConnection = client.db()
                return cb()
            })
            .catch(err => {
                console.log(err)
                return cb(err)
            })
    },
    getDb: () => dbConnection
}

I found the place that throws me this error, when I’m removing it, there’s no error:
app.js, app.get block

.then(() => {
            res.status(200).json(books)
        })

Since NetNinja has no problems, error could be triggered by different versions of Node, but I dunno for sure.
Is there a replacement to ‘.then’, that’ll let me use database?

2

Answers


  1. The error in the code you provided is that you’re sending a response (res.json({mssg: "welcome to the api"})) after making a database query. In Node.js and Express, the response should only be sent once. When you send a response, you can’t send another one.

    Login or Signup to reply.
  2. This error does not occur because of the node version or .then its occuing because you are sending a response 2 time

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

    First:

    res.json({mssg: "welcome to the api"});
    

    Second:

    res.status(200).json(books);
    

    Fix:

    just remove the second response

    app.get('/books/books', (req, res) => {
        let books = []
    
        db.collection('books')
            .find()
            .sort({ author: 1 })
            .forEach(book => books.push(book))
            .then(() => {
                res.status(200).json(books)
            })
            .catch(() => {
                res.status(500).json({error : 'Could not fetch the documents'})
            })
    
        
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search