Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

post nested object as formdata using x-www-form-urlencoded content-type

I have to send the data of post method where headers content-type is set to "x-www-form-urlencoded".

Also this form-data is nested object. e.g.

const formData = { name: "hello", email:[email protected], education: { subject: "engilsh" ... } } }

like image 716
user3913918 Avatar asked Dec 18 '25 08:12

user3913918


2 Answers

You can use the querystring module.

Post the data like this Express-like pseudocode:

const querystring = require('querystring');

// ...

router.post(
  'https://api/url',
  querystring.stringify(formData),
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
)

// EDIT: The querystring module does not work with nested objects. My bad. I'd perhaps suggest serializing the object into a JSON string.

like image 80
mkkekkonen Avatar answered Dec 20 '25 22:12

mkkekkonen


I assume that the problem you are experiencing is that the data received is shown as education: [object Object].

The easiest way to resolve this problem is to change the header from x-www-form-urlencoded to application/json. That way the object with the key education won't be serialised into [object Object]

Another way to resolve this (but hacky) is to serialise the data client side:

const formData = { name: "hello", email:[email protected], education: { subject: "engilsh" ... } } }
const formDataSerial = { raw: JSON.stringify(formData) }
// Send to server

And at the server, do another step of unpacking:

const dataSerial = formData.raw
const data = JSON.parse(dataSerial)
// Yay!
like image 28
TimNode Avatar answered Dec 20 '25 21:12

TimNode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!