I am new to express.js and I was sending data of a user using mongoose to send data to mongoDB but after I send 1 incorrect data this error pops up and If I try to send a valid user information this error pops up again but the entries are being sent to my mongoDB database.
Case 1:
- if I send a correct entry : It works
- if I send another correct entry : It works
- If I send an incorrect entry : It crashes
Case 2:
- if I send a correct entry : It works
- if I send an incorrect entry : It crashes
- If I send a correct entry : It crashes but it still sends the data to my database
So do I have to reload everytime after it crashes once or there is a better solution to that?
Error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:387:5)
at ServerResponse.setHeader (node:_http_outgoing:603:11)
at ServerResponse.header (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:794:10)
at ServerResponse.send (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:174:12)
at ServerResponse.json (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:278:15)
at Connection.onMessage (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapconnection.js:213:9)
at MessageStream.<anonymous> (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapconnection.js:59:60)
at MessageStream.emit (node:events:513:28)
at processIncomingData (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapmessage_stream.js:124:16)
at MessageStream._write (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapmessage_stream.js:33:9)
at writeOrBuffer (node:internal/streams/writable:391:12) {
index: 0,
code: 11000,
keyPattern: { email: 1 },
keyValue: { email: '[email protected]' },
[Symbol(errorLabels)]: Set(0) {}
}
Code:
index.js –
const connectToMongo = require('./db');
const express = require('express');
// npm run server
connectToMongo();
const app = express();
const port = 3000;
app.use(express.json());
// * Available Routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/notes', require('./routes/notes'));
app.listen(port, () => {
console.log(`Example app listening on port at http://localhost:${port}`)
})
db.js –
const mongoose = require('mongoose');
const mongoURI = 'mongodb://localhost:27017/iNotebook';
const connectToMongo = () =>{
mongoose.connect(mongoURI).then(()=>{
console.log('Connected to Mongo Successfully');
});
}
module.exports = connectToMongo;
routes/auth.js –
const express = require('express');
const router = express.Router();
const User = require('../models/User');
const { body, validationResult } = require('express-validator');
// * Create A User using: POST "/api/auth/". Doesn't require Auth
router.post('/',[
body('name', 'Enter a valid name').isLength({min: 3}),
body('email', 'Enter a valid email').isEmail(),
body('password', 'Password must be atleast 5 characters').isLength({min: 5})
], (req, res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
}).then(user => res.json(user))
.catch(err => console.log(err),
res.json({error: 'Please enter a unique value for Email'}))
});
module.exports = router;
routes/notes.js –
const express = require('express');
const router = express.Router();
router.get('/', (req, res)=>{
res.json([]);
});
module.exports = router;
models/Notes.js –
const mongoose = require('mongoose');
const NotesSchema = new Schema({
title:{
type: String,
required: true
},
description:{
type: String,
required: true
},
tag:{
type: String,
default: "General"
},
date:{
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('notes', NotesSchema);
models/User.js –
const mongoose = require('mongoose');
const { Schema } = mongoose;
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
date:{
type: Date,
default: Date.now
}
});
const User = mongoose.model('user', UserSchema);
User.createIndexes();
module.exports = User;