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()