How do you POST data in with Content-Type = 'application/x-www-form-urlencoded'

I know how to set the headers with ‘Content-Type’ : ’ application/x-www-form-urlencoded’ but how do I assign the body?

Edit: Figured it out

req.body =  'var1=' + encodeURIComponent(val1) +
           '&var2=' + encodeURIComponent(val2) +
           '&var3=' + encodeURIComponent(val3)

I better make a JSON serializer for this if I am to do this often.

I am in doubt about what you really want:
A) to do a GET where you send data using the querystring
B) to do a POST where you send the data using the body of the request.

Based on your data, it looks like you are trying to do A. In such a case you can add the data to the url by adding a questionmark “?” after the URL like this:

Var url = `http://www.url.com/?var1=${encodeURIComponent(myVar)}`;

Does that help you?

Thanks for the reply. Nope it’s really a POST. And based on the specs of the API I’m calling, the body of the request needs to be in that format.

Okay - could you perhaps share your finding/solution? :slight_smile:

The solution is what I’ve added to the post. Basically encode each value using encodeURIComponent.

You may want to use the “new” ES2015 feature called template literals, where you can embed JavaScript values in a string like this:

const parm = `var1=${var1}&var2=${var2}`

1 Like