Search code examples
javascriptnode.jsapicurlhttpresponse

Converting a cURL request to Node JS https request


I am running the following cURL request from terminal, which works.

curl 'https://api.bitclout.com/get-single-profile' \
-H 'Connection: keep-alive' \
-H 'Accept: application/json, text/plain, /' \
-H 'User-Agent: Mozilla/5.0 (Macintosh; Ontel Mac OS X 11_2_3) AppleWebKit/537/36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36' \
-H 'Content-Type: application/json' \
-H 'Accept-Language: en, zh-TW;q=0.8,en-US;q=0.7' \
--data-raw '{"PublicKeyBase58Check":"","Username":"elonmusk"}' \
--compressed \
--insecure

Now I am trying to convert this code to Node JS javascript https request. My converted code is as follows:

const http = require('https');

const options = {
  method: 'POST',
  hostname: 'api.bitclout.com',
  port: null,
  path: 'get-single-profile',
  headers: {
    'content-type': 'application/json',
    "PublicKeyBase58Check": 'BC1YLhKJZZcPB2WbZSSekFF19UshsmmPoEjtEqrYakzusLmL25xxAJv',
    "Username":"elonmusk"
  }
};

const req = http.request(options, res => {
    const chunks = []
  
    res.on('data', chunk => {
      chunks.push(chunk)
    })
  
    res.on('end', () => {
      const body = Buffer.concat(chunks)
      console.log(body.toString())
    })
});

However, when I run the aforementioned code I am getting the following error:

events.js:292 throw er; // Unhandled 'error' event ^

Error: socket hang up at connResetException (internal/errors.js:607:14) at TLSSocket.socketOnEnd (_http_client.js:493:23) at TLSSocket.emit (events.js:327:22) at endReadableNT (internal/streams/readable.js:1327:12) at processTicksAndRejections (internal/process/task_queues.js:80:21) Emitted 'error' event on ClientRequest instance at: at TLSSocket.socketOnEnd (_http_client.js:493:9) at TLSSocket.emit (events.js:327:22) at endReadableNT (internal/streams/readable.js:1327:12) at processTicksAndRejections (internal/process/task_queues.js:80:21) { code: 'ECONNRESET' }

Can anyone tell me what would be the code in javascript to get the same output as the cURL request?


Solution

  • This should work fine.

    var request = require('request');
    
    var headers = {
      'Connection': 'keep-alive',
      'Accept': 'application/json, text/plain, /',
      'User-Agent': 'Mozilla/5.0 (Macintosh; Ontel Mac OS X 11_2_3) AppleWebKit/537/36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36',
      'Content-Type': 'application/json',
      'Accept-Language': 'en, zh-TW;q=0.8,en-US;q=0.7'
    };
    
    var dataString = '{"PublicKeyBase58Check":"","Username":"elonmusk"}';
    
    var options = {
      url: 'https://api.bitclout.com/get-single-profile',
      method: 'POST',
      headers: headers,
      body: dataString
    };
    
    function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body);
      } 
    }
    
    request(options, callback);