We only need one dependency, the core http module. Let's require it:
const http = require('http')
Now let's define a payload we wish to POST to an endpoint:
const payload = `{
"name": "Cian O Maidín",
"company": "nearForm"
}`
Now we'll define the configuration object for the request we're about to make:
const opts = {
method: 'POST',
hostname: 'reqres.in',
port: 80,
path: '/api/users',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload)
}
}
Notice how we use Buffer.byteLength to determine the Content-Length header.
reqres.in
We're using https://reqres.in/, a dummy REST API provided as a public service. The endpoint we're posting to simply mirrors the payload back in the response.
We're using https://reqres.in/, a dummy REST API provided as a public service. The endpoint we're posting to simply mirrors the payload back in the response.
Next we'll make the request, supplying a callback handler which will be called once the request has completed:
const req = http.request(opts, (res) => {
console.log(' Status: ' + res.statusCode)
process.stdout.write(' Body: ')
res.pipe(process.stdout)
res.on('end', () => console.log(' '))
})
Let's not forget to handle errors:
req.on('error', (err) => console.error('Error: ', err))
Finally, the most important part, sending the payload:
req.end(payload)
Now if we execute our script:
$ node index.js
Providing the website reqres.in is functioning correctly, we should see something like the following:
reqres.in will simply mirror the posted payload