Making HTTP requests with Node
By Flavio Copes
Learn how to perform HTTP requests in Node.js with the built-in https module, covering GET, POST, PUT, and DELETE using https.request() and options.
~~~
I use the term HTTP, but HTTPS is what should be used everywhere, therefore these examples use HTTPS instead of HTTP.
Perform a GET Request
const https = require('https')
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'GET'
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.end()
Perform a POST Request
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
})
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
PUT and DELETE
PUT and DELETE requests use the same POST request format, and just change the options.method value.
If you want to try these requests from the command line first, I made a free route to curl tool that builds the curl command for you.
~~~
Related posts about node: