javascript - Express.js + body-parser: empty req.body from POST request -
i using express , body-parser middleware process incoming requests. on front end, have form that's hidden input , submit button (written in pug):
form(notes="savenotesform" action=`/lessons/${lesson._id}/notes` method="post" enctype="application/x-www-form-urlencoded") input(type="hidden" id="hiddennotes" name="hiddennotes" alt="notes copy" value="test").noteshidden input(type="submit" name="savenotes" alt="save notes" value="save")
on backend, have express app using body-parser:
const bodyparser = require('body-parser'); // ... app.use(bodyparser.json()); app.use(bodyparser.urlencoded({ extended: true }));
and route processing incoming request:
router.post('/lessons/:lessonid/notes', lessoncontroller.updatenotes); // ... , in lessoncontroller: exports.updatenotes = async (req, res) => { console.log('updatenotes request received'); console.log(req.body); res.status(200).json({ status: 'success' }); }
when try use req.body
in updatenotes
, body empty object, should @ least have property hiddennotes
value "test"
. please comment if have questions or think see problem!
[updated]
this silly mistake, forgot had written separate event handler when form gets submitted - took me posting on before went through of code :) event handler uses axios , looks this:
const savenotesbutton = $('form.savenotes'); savenotesbutton.on('submit', ajaxsavenotes); function ajaxsavenotes(e) { e.preventdefault(); axios .post(this.action) .then(res => { console.log(res.data); }) .catch(console.error); }
unfortunately, when making post
s axios, need include data in object this, or else won't included in request:
const savenotesbutton = $('form.savenotes'); savenotesbutton.on('submit', ajaxsavenotes); function ajaxsavenotes(e) { e.preventdefault(); axios .post(this.action, { notes: this.children.hiddennotes.value }) // data added here .then(res => { console.log(res.data); }) .catch(console.error); }
have tried querying end point using postman or similar?
Comments
Post a Comment