Proxy with nodejs Proxy with nodejs express express

Proxy with nodejs


Take a look at the readme for http-proxy. It has an example of how to call proxyRequest:

proxy.proxyRequest(req, res, {  host: 'localhost',  port: 9000});

Based on the error message, it sounds like you're passing a bogus domain name into the proxyRequest method.


Other answers are slightly outdated.

Here's how to use http-proxy 1.0 with express:

var httpProxy = require('http-proxy');var apiProxy = httpProxy.createProxyServer();app.get("/api/*", function(req, res){   apiProxy.web(req, res, { target: 'http://google.com:80' });});


Here is an example of the proxy which can modify request/response body.

It evaluates through module which implements transparent read/write stream.

var http = require('http');var through = require('through');http.createServer(function (clientRequest, clientResponse) {    var departureProcessor = through(function write(requestData){        //log or modify requestData here        console.log("=======REQUEST FROM CLIENT TO SERVER CAPTURED========");        console.log(requestData);        this.queue(requestData);    });    var proxy = http.request({ hostname: "myServer.com", port: 80, path: clientRequest.url, method: 'GET'}, function (serverResponse) {        var arrivalProcessor = through(function write(responseData){            //log or modify responseData here            console.log("======RESPONSE FROM SERVER TO CLIENT CAPTURED======");            console.log(responseData);            this.queue(responseData);        });        serverResponse.pipe(arrivalProcessor);        arrivalProcessor.pipe(clientResponse);    });    clientRequest.pipe(departureProcessor, {end: true});    departureProcessor.pipe(proxy, {end: true});}).listen(3333);