Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS equivalent of a curl request

I am trying to convert a curl request to a nodeJS script, but somehow it fails on me., by failing means, that the url I setup with cloudflare triggers a captcha whilst it doesn't when I use the curl request I copied from dev tools > network tab.

here is the curl

curl -q 'https://foo.bar/path' -H 'cookie: somecookie' -H 'origin: https://foo.bar' -H 'accept-encoding: gzip, deflate, br' -H 'accept-language: en-US,en;q=0.9,pt;q=0.8' -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' -H 'content-type: application/x-www-form-urlencoded; charset=UTF-8' -H 'accept: */*' -H 'referer: https://foo.bar/path' -H 'authority: www.foo.bar' -H 'x-requested-with: XMLHttpRequest' --data "foo=bazz" --compressed

and here is the nodeJS code

var request = require('request');
var url = 'https://foo.bar/path';
var cookie = 'somecookie';
var ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36';

var baseRequest = request.defaults({
  headers: {
    'Cookie': cookie,
    'User-Agent': ua,
    'origin': 'https://foo.bar',
    'referer': 'https://foo.bar/path'
  }
});

baseRequest.post({ url: url, formData: {
  foo: 'bazz'
}}, function(err, response, body) {
  console.log(body);
});
like image 986
Joey Hipolito Avatar asked Jan 28 '23 22:01

Joey Hipolito


1 Answers

There are some online tools that doing it for you like https://curl.trillworks.com/#node

by the way I did for you and the result is :

var request = require('request');

var headers = {
    'cookie': 'somecookie',
    'origin': 'https://foo.bar',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9,pt;q=0.8',
    'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'accept': '*/*',
    'referer': 'https://foo.bar/path',
    'authority': 'www.foo.bar',
    'x-requested-with': 'XMLHttpRequest'
};

var dataString = 'foo=bazz';

var options = {
    url: 'https://foo.bar/path',
    method: 'POST',
    headers: headers,
    body: dataString
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);
like image 195
Mini Avatar answered Feb 05 '23 18:02

Mini