I am trying to get a post router to insert a comment in a MongoDB database with Mongoose. When I try to run my Post router, it seems the name of the input field goes into req.body.newComment, but the value itself is empty.
Result of POST IN app:

However when I try to run this in Postman with x-www-form-urlencoded it can read the value and succesfully save the Document to MongoDB.
Result of Postman:

Currently in ./app.js I am using the following lines to use body-parser
var bodyParser = require('body-parser');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
In my router file, I have both a GET and POST router for the same link, using a :parameter for dynamically getting a Document out of MongoDB. With the req.params I then build a findOne query to fetch info from MongoDB. This leads into a page with a form where questions can be submitted, for the POST router. My GET router is working as intended so far.
My current POST router:
router.post('/kweeni/:questionTitle', function (req, res, next) {
let c = new Comment()
c.text = req.body.newComment,
c.user_id = 1,
c.question_id = 1
c.save(function (err, doc) {
res.json(doc)
});
});
Does anyone have an idea how this could be fixed?
Thanks in advance!
I have found a solution! After temporary removing my front end JS script in my PUG file, the POST router correctly received the value of req.body.questionTitle!
On my script I've written an event listener which clears the input field of the form after submitting the data. It seems that the POST router receives the field after the event listener resets it, and thus the value was empty. As Postman didn't use the front end script, it didn't come across this issue and normally worked.
To solve this I've added a 1ms delay with a Timeout function around the emptying of the input field!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With