hritik pawar
hritik pawar

Reputation: 19

Cannot set headers after they are sent to the client ( Nodejs , MongoDb , Express)

I am trying Learning Nodejs and MongoDb. So what I did is created a simple Webpage which saves quotes to MongoDb and retrieves it. But I am unable to get data from MongoDb I am getting the Nodejs Error which says

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the 
client
    at ServerResponse.setHeader (_http_outgoing.js:485:11)
    at ServerResponse.writeHead (_http_server.js:269:21)
    at C:\Hritik\programming\Advanced Web\FirstMern\server.js:18:25
    at processTicksAndRejections (internal/process/task_queues.js:94:5) {    
  code: 'ERR_HTTP_HEADERS_SENT'
}

< Server.js>

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

MongoClient.connect('mongodb+srv://{Username}:{password}@cluster0.vmmbl.mongodb.net/<dbname>?retryWrites=true&w=majority', { useUnifiedTopology: true })
    .then(client => {

        console.log('Connected to Database')
        const db = client.db('star-wars-quotes')
        app.set('view engine', 'ejs')
        app.use(bodyParser.urlencoded({ extended: true }))

        app.get('/', (req, res) => {
            res.sendFile('C:/Hritik/programming/Advanced Web/FirstMern' + '/index.html')
            db.collection('quotes').find().toArray()
                .then(results => {
                    res.writeHead(200, { 'Content-Type': 'text/html' });
                    res.render('index.ejs', { quotes: results })
                    res.end();
                })
                .catch(error => console.error(error))
        });
        app.post('/quotes', (req, res) => {
            db.collection('quotes').insertOne(req.body, (err, result) => {
                if (err) return res.end();
                console.log('saved to database')
                res.redirect('/')
            })
        });
        app.listen(3000, function() {
            console.log('listening on 3000')
        })
    })
    .catch(console.error)

Upvotes: 0

Views: 149

Answers (4)

Shishir Aithal
Shishir Aithal

Reputation: 122

The SHORT Answer is, Once the line res.render("...") is executed do not try to write res.send("...") or res.end() as res.render() already ends the request.

Upvotes: 0

Namit Piriya
Namit Piriya

Reputation: 141

One of the way that I find very helpful that when you are sending a response or rendering something you can place return before that so the function will not go after the return statement example:-

return res.status(200).json({success:true, msg:"something good happened"})

Upvotes: 0

user14520680
user14520680

Reputation:

Both Response.prototype.end and Response.prototype.render end the request. You obviously cannot send headers twice (each response sends headers), so remove res.end().

Upvotes: 0

jfriend00
jfriend00

Reputation: 707288

Remove the res.end() that's after your call to res.render() because res.render() already ends the request and trying to end it again is causing your warning message.

Upvotes: 1

Related Questions