0

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)
  • duplicate of https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client – Someone Special Nov 22 '20 at 07:23
  • Very nice way to learn. Using `cluster0.vmmbl` someone could try to log into your cluster. `srv` strings I believe are `--tls` enabled, otherwise the password is sent in clear text. – Minsky Nov 22 '20 at 07:38

3 Answers3

1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • @hritikpawar - Did this answer your question? If so, you can indicate that to the community by clicking the checkmark to the left of the answer and that will also earn you some reputation points here for following the proper procedure. – jfriend00 Feb 28 '21 at 01:38
0

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().

0

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"})

Namit Piriya
  • 141
  • 7