dev-resources.site
for different kinds of informations.
Making simple HTTP requests in NodeJS
Published at
8/8/2021
Categories
node
xhr
http
https
Author
vishalraj82
Author
11 person written this
vishalraj82
open
Of course, there are numerous npm packages available to make HTTP requests. Just to name a few, you can use
many more. These all are super fantastic libraries which bring in array of capabilities on how to make HTTP request and handle various responses and errors.
But sometimes, all we need is, a simple HTTP/S request and response handler. This can be easily done with NodeJS's built-in packages http / https with a very simple lean piece of code. Lets see it in action.
NOTE: Since Promise
is fancy, so I am gonna use it for this.
// SimpleHttp.js
const { URL } = require('url'),
http = require('http'),
https = require('https');
/**
* Simple function to make HTTP / HTTPS request.
*
* @param {String} url The url to be scraped
* @param {Object} config The configuration object to make HTTP request
*
* @return {Promise}
*/
module.exports = function fetch (url, config = {}) {
const u = new URL(url),
secure = 'https:' === u.protocol,
handler = secure ? https : http,
options = {
method: config.method || 'GET',
host: u.hostname,
port: u.port || (secure ? 443 : 80),
path: u.pathname,
query: config.query || {},
},
isHeadRequest = 'HEAD' === options.method;
return new Promise((resolve, reject) => {
const request = handler.request(options, function (response) {
const status = parseInt(response.statusCode, 10);
if ([301, 302, 307].includes(status)) {
resolve(load(response.headers.location, options));
} else if (status < 200 || response >= 400) {
reject(new Error(`Unexpected response, got HTTP ${status}`));
} else {
if (isHeadRequest) {
resolve({ headers: response.headersn} );
} else {
const chunks = [];
response.on('data', function onData (chunk) {
chunks.push(chunk);
});
response.on('end', function onEnd () {
resolve({
status,
body: Buffer.concat(chunks).toString('utf8')
});
});
}
}
});
if (options.postBody) {
request.write(postBody);
}
request.on('error', reject);
request.end();
});
}
And that will be all.
EDIT: Added support to follow if server responds with HTTP redirect.
xhr Article's
11 articles in total
A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX
read article
2่กไปฃ็ ๏ผ่งฃๅณ้ๆๅฒ็ช๏ผ่ชๅจๅธฎไฝ ๅๆถ้ๅค็่ฟๆ่ฏทๆฑ
read article
How to Target XHR Errors in Cypress
read article
Angular SSR Refused to set unsafe header
read article
What Is XHR And Why You Should Be Looking At XMLHttpRequests
read article
Making simple HTTP requests in NodeJS
currently reading
Ajax and XHR using plain JS
read article
Intro to Ajax & XHR
read article
OMDb-search (JS code demo)
read article
Is it possible to build an application with Webpack that uses XHR to load pages of the site? If so, which plugins do you use?
read article
Sending cookies with Cross Origin (CORS) request
read article
Featured ones: