Home > Net >  How to make a http get request using node without 'require'
How to make a http get request using node without 'require'

Time:11-21

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 ?

CodePudding user response:

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.

CodePudding user response:

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}`);
});
  • Related