0
votes

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" ... } } }

2

2 Answers

0
votes

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.

0
votes

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!