K
K
kyzinatra2020-09-21 10:06:19
JavaScript
kyzinatra, 2020-09-21 10:06:19

How to proxy outgoing request on Nodejs?

I need to change the ip that I send when requesting a site through
the request library (node.js)
Now the request looks like this.

const request = require("request");
request ({
    url: "https://2ip.ru/",
    headers: {
      "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4083.112 Safari/535.36",
    },
  }, (err, res, body) => {
  console.log(res.statusCode);
  if (err) reject(err);
  resolve(cheerio.load(body, { decodeEntities: false }));
});


I tried to proxy through tunnel:
const request = require("request");
const tunnel = require("tunnel");
const tunnelingAgent = tunnel.httpsOverHttp({
  proxy: {
    host: "203.150.180.225",
    port: 3128,
  },
});
request (
  {
    url: "https://2ip.ru/",
    headers: {
      agent: tunnelingAgent,
      "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4083.112 Safari/535.36",
    },
  },
  (err, res, body) => {
    console.log(res.statusCode);
    if (err) reject(err);
    resolve(cheerio.load(body, { decodeEntities: false }));
  }
);


But apparently I'm doing something wrong. because I didn't get the desired result.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lynn "Coffee Man", 2020-09-21
@kyzinatra

https://nodejs.org/api/http.html#http_http_request...
agent should be in options , not headers

request({
  agent: tunnelingAgent,
  url: "https://2ip.ru/",
  headers: { ... }
}, callback);

R
Robur, 2020-09-21
@Robur

request has a "proxy" parameter
and a large section in the docs
https://github.com/request/request#proxies

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question