Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I did not get the difference between https.get() vs https.request() methods of nodejs npm package https

    // # Nodejs Program 1
const https = require('https');

https.get('https://www.google.com/', (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });

}).on('error', (e) => {
    console.error(e);
});
// # Nodejs Program 2
const options = {
    hostname: 'www.google.com',
    port: 443,
    path: '/',
    method: 'GET'
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});
req.end();

Both program 1 and program 2 giving me the same output. I want to know the difference between https.get() and https.request() of https package.

like image 424
Atharva Jawalkar Avatar asked Oct 17 '25 18:10

Atharva Jawalkar


2 Answers

See the documentation:

Like http.get() but for HTTPS.

and http.get says:

Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and calls req.end() automatically.

like image 144
Quentin Avatar answered Oct 20 '25 10:10

Quentin


"https.get" is only for GET requests - which are a special type of HTTP request that should be used only for retrieving data.

in "https.request" you can specify any HTTP method you want in the 'method' property - you could use "POST" (creating), PATCH (updating) or also GET.

More information here:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

like image 22
J Marlow Avatar answered Oct 20 '25 09:10

J Marlow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!