0

This question is similar to the below question, but for Node.js e.g. version 8.11.1

How to make an HTTP get request in C without libcurl?

Are there any tricks using JS without the use of require('http') to make a simple GET request with headers and read response ?

asudhak
  • 2,929
  • 4
  • 22
  • 27

2 Answers2

2

You can make an http request without the http module in a node script, by using an underlying client on the operating system. This is not "pure" node.js - but is a pragmatic answer I guess.

const { exec } = require('child_process');

exec('curl -v -i https://stackoverflow.com', (error, stdout, stderr) => {
  if (error) {
    console.error(`error: ${error.message}`);
    return;
  }

  if (stderr) {
    console.error(`stderr: ${stderr}`);
    return;
  }

  console.log(`stdout:\n${stdout}`);
});
madflow
  • 7,718
  • 3
  • 39
  • 54
1

What you would expect to use in such a case, is the raw XMLHttpRequest. Unfortunately Node.js does not provide XHR API as we know it from the Browser. Same goes with window.fetch() API. There are a few npm libraries out there (node-xmlhttprequest or node-fetch) to overcome this, and help with code reusability, but if you look into their source code, you'll see that internally they also have the require('http').

So I'm not sure if what you want is possible. Of course, unless you dig inside the code of the http module and write your own version of it.

Mihai Paraschivescu
  • 1,261
  • 13
  • 12