How to make http request with Node.js

How to make a simple http GET or POST request with Nodejs without external libraries. We will use the Nodejs built in http module.

Require

const http = require("http")

Example

const http = require("http")

const agent = new http.Agent({
    keepAlive: true,
    maxSockets: 5
})

const json = JSON.stringify({data: "data"})

const options = {
    agent: agent,
    method: 'POST',
    hostname: "mockbin.com",
    path: '/request',
    port: 80,
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(json),
    },
}
const callback = function (response) {
    let out = ''
    response.on('data', function (chunk) {
        out += chunk
    })
    response.on('end', function () {
        if (response.statusCode === 200) {
            console.log(out)
        } else {
            console.log('error')
        }
    })
}


const req = http.request(options, callback)
req.on('error', (error) => {
    console.log('error')
})
req.on('timeout', () => {
    req.abort()
});
req.write(json)
req.end()

Node fetch for http request

Starting from Nodejs v18.0.0 you can also use the fetch node api, that makes it really easy and fast doing http requests using node.

const response = await fetch(URL HERE)
const data = await response.text()

console.log(response.status)
console.log(data)

Once done the http request, you can access the data by using: