Wednesday, 24 May 2017

Translating PHP+CURL proxy request into javascript/node.js

I'm currently translating some PHP code into javascript (node.js). I need to recreate a request being sent using PHP's httpful library (which internally uses CURL) with the http module of node.js.

The PHP code includes this:

$request = Request::get($someUrl);
.
.
.
// This line enables the CURL --proxy option
$request->addOnCurlOption(CURLOPT_PROXY, $someProxyAddress);

How do I recreate CURL's --proxy functionality using the http module of node.js? Is it just a matter of setting some headers and then sending the request to $someProxyAddress instead of $someUrl?

Here's how my node.js code is looking:

var someJsonBody = getSomeJsonBodyContent();
var someHostName = getSomeHostName();
var somePort = getSomePort();
var somePath = getSomePath();
var someProxyAddress = getSomeProxyAddress(); // THIS IS UNUSED!! :(

var httpOptions = {
    method: 'GET',
    host: someHostName, // WRONG - I want this request to go to `someProxyAddress`
    port: somePort,
    path: somePath,
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(someJsonBody)
    }
};

var req = http.request(httpOptions, someFunctionToHandleResponse);
req.write(someJsonBody);
req.end();

The http.request method does support any proxy-related option in httpOptions. How do I cause this request to be properly proxied, the same as CURL's --proxy option?

Links:

PHP Httpful: http://phphttpclient.com/

Node.js http: https://nodejs.org/api/http.html



via Gershom Maes

No comments:

Post a Comment