Как использовать node-http-proxy для маршрутизации HTTP-HTTPS?

Вот версия модуля, которую я использую:

$ npm list -g | grep proxy
├─┬ [email protected]

Веб-служба вызывает мою машину, и моя задача состоит в том, чтобы передать запрос другому URL-адресу и хосту с дополнительным параметром запроса на основе содержимого тела запроса:

var http      = require('http'),
    httpProxy = require('http-proxy')
    form2json = require('form2json');

httpProxy.createServer(function (req, res, proxy) {
  // my custom logic
  var fullBody = '';
  req.on('data', function(chunk) {
      // append the current chunk of data to the fullBody variable
      fullBody += chunk.toString();
  });
  req.on('end', function() {
      var jsonBody = form2json.decode(fullBody);
      var payload = JSON.parse(jsonBody.payload);
      req.url = '/my_couch_db/_design/ddoc_name/_update/my_handler?id="' + payload.id + '"';

      // standard proxy stuff
      proxy.proxyRequest(req, res, {
        changeOrigin: true,
        host: 'my.cloudant.com',
        port: 443,
        https: true
      });
  });
}).listen(8080);

Но я продолжаю сталкиваться с такими ошибками, как: An error has occurred: {"code":"ECONNRESET"}

У кого-нибудь есть идеи о том, что здесь нужно исправить?


person pulkitsinghal    schedule 04.04.2013    source источник


Ответы (3)


Это помогло мне:

var httpProxy = require('http-proxy');

var options = {
  changeOrigin: true,
  target: {
      https: true
  }
}

httpProxy.createServer(443, 'www.google.com', options).listen(8001);
person Aaron Shafovaloff    schedule 06.09.2013
comment
Спасибо, Аарон, это первый полезный ответ, который я получил по этой теме за долгое время, и тот, который действительно работает! - person pulkitsinghal; 10.09.2013

Чтобы перенаправить все запросы, поступающие на порт 3000, на порт https://google.com:

const https = require('https')
const httpProxy = require('http-proxy')

httpProxy.createProxyServer({
  target: 'https://google.com',
  agent: https.globalAgent,
  headers: {
    host: 'google.com'
  }
}).listen(3000)

Пример вдохновлен https://github.com/nodejitsu/node-http-proxy/blob/master/examples/http/proxy-http-to-https.js.

person Ryan Walls    schedule 21.05.2014

После некоторых проб и ошибок это сработало для меня:

var fs = require('fs')
var httpProxy = require('http-proxy');
var https = require('https');

var KEY  = 'newfile.key.pem';
var CERT = 'newfile.crt.pem';

httpProxy.createServer({
  changeOrigin: true,
  target: 'https://example.com',
  agent: new https.Agent({
    port: 443,
    key: fs.readFileSync(KEY),
    cert: fs.readFileSync(CERT)
  })
}).listen(8080);
person raine    schedule 24.08.2015