提问者:小点点

curl请求的NodeJS等价物


我正在尝试将curl请求转换为nodeJS脚本,但不知何故,它在我身上失败了。通过失败的方式,我用cloudflare设置的url触发了验证码,而当我使用从dev tools复制的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

下面是nodeJS代码

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);
});

共2个答案

匿名用户

有一些在线工具可以帮你做这件事,比如https://curl.trillworks.com/#node

顺便说一下,我为你做了什么,结果是:

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);

匿名用户

exec(`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`
, (error, result, metadata) => {
      console.log(result);
    });

您可以使用exec直接卷曲