Answer the question
In order to leave comments, you need to log in
Why is it not possible to read data from req.body?
This piece of code worked and suddenly stopped working. I can't figure out what's the reason
router.post('/', function (req, res, next) {
email.find({email: req.body.email}, function(err, data) {
if(data[0].email === req.body.email) {
res.send('Email exist!');
} else {
var dbData = new email({email: req.body.email});
dbData.save(function (err, dbData, affected) {
res.send(dbData);
console.log(dbData);
});
}
});
});
app-0 (entire): TypeError: Cannot read property 'email' of undefined
app-0 (entire): at saveEmail (/var/www/app/routes/index.js:20:19)
app-0 (entire): at Promise.<anonymous> (/var/www/app/routes/index.js:32:9)
app-0 (entire): at Promise.<anonymous> (/var/www/app/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
app-0 (entire): at Promise.emit (events.js:95:17)
app-0 (entire): at Promise.emit (/var/www/app/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
app-0 (entire): at Promise.fulfill (/var/www/app/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
app-0 (entire): at Object.cb (/var/www/app/node_modules/mongoose/lib/query.js:1010:22)
app-0 (entire): at Object._onImmediate (/var/www/app/node_modules/mongoose/node_modules/mquery/lib/utils.js:137:16)
app-0 (entire): at processImmediate [as _immediateCallback] (timers.js:354:15)
email.find({email: req.body.email}, function(err, data) {
if(data.length !== 0 && data[0].email === req.body.email) {
res.send('Email exist!');
} else {
var dbData = new email({email: req.body.email});
dbData.save(function (err, dbData, affected) {
res.send(dbData);
console.log(dbData);
});
}
});
Answer the question
In order to leave comments, you need to log in
It's strange that it worked before and "suddenly" stopped working. In general, judging by the code, you are using expressjs. The documentation says expressjs.com/4x/api.html#req.body:
"req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body- parsing middleware such as body-parser and multer."
That is, body is undefined by default and needs to be filled with something like body-parser.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question