writingsabout

A

AZRULAZIZ

Software Developer

How to send POST request using cURL with Express.js & axios

16 March, 2020

If you use Express & axios, sending post request in the raw JSON format to a third-party API that only accept cURL request wont work.

// this wont work if the API only accept request via cURL

const data = {
    prop1: "value1",
    prop2: "value2"
}

axios.post(endpoint, data)

To make it work, first create a config object and set the content type of the post body in the headers like this:

const config = {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}

Then, import the querystring module that is already built into the node standard library.

We'll use the querystring.stringify() method that will produce a URL query string from the given object.


Finally, send the post request using axios. Pass the raw JSON data into the method & dont forget to include the config object.

const qs = require('querystring');

const obj = {
    prop1: "value1",
    prop2: "value2"
}

// stringify method produce url query string when we pass an object 
console.log(qs.stringify(obj)) // prop1=value1&prop2=value2

axios.post(endpoint, qs.stringify(obj), config)