(PLEASE HELP ME TO SOLVE THIS ERROR OF MONGOOSE)
Node.js v18.8.0
PS C:Users97798DesktopCWH_WEB_DEVLOPMENTExpressDANCE__WEBSITE> node app.js
body-parser deprecated undefined extended: provide extended option app.js:40:17
The application started successfully on port 8000
node:internal/errors:484
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:393:5)
at ServerResponse.setHeader (node:_http_outgoing:607:11)
at ServerResponse.header (C:Users97798DesktopCWH_WEB_DEVLOPMENTExpressDANCE__WEBSITEnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (C:Users97798DesktopCWH_WEB_DEVLOPMENTExpressDANCE__WEBSITEnode_modulesexpresslibresponse.js:174:12)
at C:Users97798DesktopCWH_WEB_DEVLOPMENTExpressDANCE__WEBSITEapp.js:81:17
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: ‘ERR_HTTP_HEADERS_SENT’
}
And This is my Backend Code Using Mongoose,Express,pug and node.js.
I HAVE A ABOVE ERROR IN THIS BELOW APP.JS CODE.{PLEASE HELP ME GUYS.}
const express = require(“express”);
const path = require(“path”);
const mongoose = require(‘mongoose’);
const bodyparser = require(“body-parser”);
main().catch(err => console.log(err));
async function main() {
mongoose.connect(‘mongodb://localhost:27017/contactDance’);
}
const app = express();
const port = 8000;
// Define mongoose schema
const contactSchema = new mongoose.Schema({
name: String,
phone:String,
email:String,
address:String,
desc:String
});
const Contact = mongoose.model(‘Contact’, contactSchema);
app.use(‘/static’, express.static(‘static’))
app.use(express.urlencoded())
app.set(‘view engine’, ‘pug’) // Set the template engine as pug
app.set(‘views’, path.join(__dirname, ‘views’)) // Set the views directory
app.get(‘/’, (req, res)=>{
const params = { }
res.status(200).render(‘home.pug’, params);
})
app.get(‘/contact’, (req, res)=>{
const params = { }
res.status(200).render(‘contact.pug’, params);
})
app.post(‘/contact’, (req, res)=>{
var myData =new Contact(req.body);
myData.save().then(()=>{
res.send(“This item has been saved in the database.”)
})
.catch(()=>{
res.status(400).send(“Item was not saved to the database.”)
})
res.status(200).render(‘contact.pug’);
})
// START THE SERVER
app.listen(port, ()=>{
console.log(`The application started successfully on port ${port}`);
});
const express = require(“express”);
const path = require(“path”);
const mongoose = require(‘mongoose’);
const bodyparser = require(“body-parser”);
main().catch(err => console.log(err));
async function main() {
mongoose.connect(‘mongodb://localhost:27017/contactDance’);
}
const app = express();
const port = 8000;
// Define mongoose schema
const contactSchema = new mongoose.Schema({
name: String,
phone:String,
email:String,
address:String,
desc:String
});
const Contact = mongoose.model(‘Contact’, contactSchema);
app.use(‘/static’, express.static(‘static’))
app.use(express.urlencoded())
app.set(‘view engine’, ‘pug’) // Set the template engine as pug
app.set(‘views’, path.join(__dirname, ‘views’)) // Set the views directory
app.get(‘/’, (req, res)=>{
const params = { }
res.status(200).render(‘home.pug’, params);
})
app.get(‘/contact’, (req, res)=>{
const params = { }
res.status(200).render(‘contact.pug’, params);
})
app.post(‘/contact’, (req, res)=>{
var myData =new Contact(req.body);
myData.save().then(()=>{
res.send(“This item has been saved in the database.”)
})
.catch(()=>{
res.status(400).send(“Item was not saved to the database.”)
})
res.status(200).render(‘contact.pug’);
})
// START THE SERVER
app.listen(port, ()=>{
console.log(`The application started successfully on port ${port}`);
});
First, use express.json() instead of body parser.
Second, The “Cannot set headers after they are sent to the client” error occurs when the server sends more than one response for a single request.
In your post /contact route, you’re sending response twice i.e. first – after saving in database (res.send(“The item has been saved in the database.”) and then again at res.status(200).render(“contact.pug”).
To solve this error, send only one response for each request. Just remove the first response and your app should work fine.