Node_Js Http Proxy

Datacenter proxies

  • HTTP & SOCKS
  • Price $1.3/IP
  • Locations: DE, RU, US
  • 5% OFF coupon: APFkysWLpG

Visit proxy6.net

http-proxy – npm

-proxy1. 18. 1 • Public • Published a year ago Readme Explore BETA3 Dependencies2, 292 Dependents85 Versions
node–proxy is an HTTP programmable proxying library that supports
websockets. It is suitable for implementing components such as reverse
proxies and load balancers.
Table of Contents
Installation
Upgrading from 0. 8. x?
Core Concept
Use Cases
Setup a basic stand-alone proxy server
Setup a stand-alone proxy server with custom server logic
Setup a stand-alone proxy server with proxy request header re-writing
Modify a response from a proxied server
Setup a stand-alone proxy server with latency
Using HTTPS
Proxying WebSockets
Options
Listening for proxy events
Shutdown
Miscellaneous
Test
ProxyTable API
Logo
Contributing and Issues
License
npm install -proxy –save
Back to top
Click here
A new proxy is created by calling createProxyServer and passing
an options object as argument (valid properties are available here)
var Proxy = require(‘-proxy’);var proxy = eateProxyServer(options);
†Unless listen(.. ) is invoked on the object, this does not create a webserver. See below.
An object will be returned with four methods:
web req, res, [options] (used for proxying regular HTTP(S) requests)
ws req, socket, head, [options] (used for proxying WS(S) requests)
listen port (a function that wraps the object in a webserver, for your convenience)
close [callback] (a function that closes the inner webserver and stops listening on given port)
It is then possible to proxy requests by calling these functions
eateServer(function(req, res) { (req, res, { target: ”});});
Errors can be listened on either using the Event Emitter API
(‘error’, function(e) {… });
or using the callback API
(req, res, { target: ”}, function(e) {… });
When a request is proxied it follows two different pipelines (available here)
which apply transformations to both the req and res object.
The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.
The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
to the client.
var = require(”), Proxy = require(‘-proxy’);eateProxyServer({target:’localhost:9000′})(8000); eateServer(function (req, res) { res. writeHead(200, { ‘Content-Type’: ‘text/plain’}); (‘request successfully proxied! ‘ + ‘n’ + ringify(req. headers, true, 2)); ();})(9000);
†Invoking listen(.. ) triggers the creation of a web server. Otherwise, just the proxy instance is created.
This example shows how you can proxy a request using your own HTTP server
and also you can put your own logic to handle the request.
var = require(”), Proxy = require(‘-proxy’);var proxy = eateProxyServer({});var server = eateServer(function(req, res) { (req, res, { target: ”});});(“listening on port 5050″)(5050);
This example shows how you can proxy a request using your own HTTP server that
modifies the outgoing proxy request by adding a special header.
var = require(”), Proxy = require(‘-proxy’);var proxy = eateProxyServer({});(‘proxyReq’, function(proxyReq, req, res, options) { tHeader(‘X-Special-Proxy-Header’, ‘foobar’);});var server = eateServer(function(req, res) { (req, res, { target: ”});});(“listening on port 5050″)(5050);
Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.
Harmon allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.
var = require(”), Proxy = require(‘-proxy’);var proxy = eateProxyServer();eateServer(function (req, res) { setTimeout(function () { (req, res, { target: ‘localhost:9008’});}, 500);})(8008);eateServer(function (req, res) { res. writeHead(200, { ‘Content-Type’: ‘text/plain’}); (‘request successfully proxied to: ‘ + + ‘n’ + ringify(req. headers, true, 2)); ();})(9008);
You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set secure: true in the options.
HTTPS -> HTTP
eateServer({ target: { host: ‘localhost’, port: 9009}, ssl: { key: adFileSync(”, ‘utf8’), cert: adFileSync(”, ‘utf8’)}})(8009);
HTTPS -> HTTPS
eateServer({ ssl: { key: adFileSync(”, ‘utf8’), cert: adFileSync(”, ‘utf8’)}, target: ‘localhost:9010’, secure: true})(443);
HTTP -> HTTPS (using a PKCS12 client certificate)
eateProxyServer({ target: { protocol: ‘:’, host: ‘my-domain-name’, port: 443, pfx: adFileSync(‘path/to/certificate. p12’), passphrase: ‘password’, }, changeOrigin: true, })(8000);
You can activate the websocket support for the proxy using ws:true in the options.
eateServer({ target: ‘wslocalhost:9014’, ws: true})(8014);
Also you can proxy the websocket requests just calling the ws(req, socket, head) method.
var proxy = new eateProxyServer({ target: { host: ‘localhost’, port: 9015}});var proxyServer = eateServer(function (req, res) { (req, res);});(‘upgrade’, function (req, socket, head) { (req, socket, head);});(8015);
eateProxyServer supports the following options:
target: url string to be parsed with the url module
forward: url string to be parsed with the url module
agent: object to be passed to (s). request (see Node’s agent and agent objects)
ssl: object to be passed to eateServer()
ws: true/false, if you want to proxy websockets
xfwd: true/false, adds x-forward headers
secure: true/false, if you want to verify the SSL Certs
toProxy: true/false, passes the absolute URL as the path (useful for proxying to proxies)
prependPath: true/false, Default: true – specify whether you want to prepend the target’s path to the proxy path
ignorePath: true/false, Default: false – specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).
localAddress: Local interface string to bind for outgoing connections
changeOrigin: true/false, Default: false – changes the origin of the host header to the target URL
preserveHeaderKeyCase: true/false, Default: false – specify whether you want to keep letter case of response header key
auth: Basic authentication i. e. ‘user:password’ to compute an Authorization header.
hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects.
autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.
protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to ” or ”. Default: null.
cookieDomainRewrite: rewrites domain of set-cookie headers. Possible values:
false (default): disable cookie rewriting
String: new domain, for example cookieDomainRewrite: “”. To remove the domain, use cookieDomainRewrite: “”.
Object: mapping of domains to new domains, use “*” to match all domains.
For example keep one domain unchanged, rewrite one domain and remove other domains:cookieDomainRewrite: {
“”: “”,
“*”: “”}
cookiePathRewrite: rewrites path of set-cookie headers. Possible values:
String: new path, for example cookiePathRewrite: “/newPath/”. To remove the path, use cookiePathRewrite: “”. To set path to root use cookiePathRewrite: “/”.
Object: mapping of paths to new paths, use “*” to match all paths.
For example, to keep one path unchanged, rewrite one path and remove other paths:cookiePathRewrite: {
“/”: “/”,
headers: object with extra headers to be added to target requests.
proxyTimeout: timeout (in millis) for outgoing proxy requests
timeout: timeout (in millis) for incoming requests
followRedirects: true/false, Default: false – specify whether you want to follow redirects
selfHandleResponse true/false, if set to true, none of the webOutgoing passes are called and it’s your responsibility to appropriately return the response by listening and acting on the proxyRes event
buffer: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e. g. If you read the body of a request into a field called ‘req. rawbody’ you could restream this field in the buffer option:
‘use strict’;
const streamify = require(‘stream-array’);
const HttpProxy = require(‘-proxy’);
const proxy = new HttpProxy();
module. exports = (req, res, next) => {
(req, res, {
target: ‘localhost:4003/’,
buffer: streamify(req. rawBody)}, next);};
NOTE:
and are optional.
and rward cannot both be missing
If you are using the method, the following options are also applicable:
error: The error event is emitted if the request to the target fail. We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.
proxyReq: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to “web” connections
proxyReqWs: This event is emitted before the data is sent. Applies to “websocket” connections
proxyRes: This event is emitted if the request to the target got a response.
open: This event is emitted once the proxy websocket was created and piped into the target websocket.
close: This event is emitted once the proxy websocket was closed.
(DEPRECATED) proxySocket: Deprecated in favor of open.
var Proxy = require(‘-proxy’);var proxy = eateServer({ target:’localhost:9005′});(8005);(‘error’, function (err, req, res) { res. writeHead(500, { ‘Content-Type’: ‘text/plain’}); (‘Something went wrong. And we are reporting a custom error message. ‘);});(‘proxyRes’, function (proxyRes, req, res) { (‘RAW Response from the target’, ringify(proxyRes. headers, true, 2));});(‘open’, function (proxySocket) { (‘data’, hybiParseAndLogMessage);});(‘close’, function (res, socket, head) { (‘Client disconnected’);});
When testing or running server within another program it may be necessary to close the proxy.
This will stop the proxy from accepting new connections.
var proxy = new eateProxyServer({ target: { host: ‘localhost’, port: 1337}});();
If you want to handle your own response after receiving the proxyRes, you can do
so with selfHandleResponse. As you can see below, if you use this option, you
are able to intercept and read the proxyRes but you must also make sure to
reply to the res itself otherwise the original client will never receive any
data.
Modify response
var option = { target: target, selfHandleResponse: true}; (‘proxyRes’, function (proxyRes, req, res) { var body = []; (‘data’, function (chunk) { (chunk);}); (‘end’, function () { body = (body). toString(); (“res from proxied server:”, body); (“my response to cli”);});}); (req, res, option);
A proxy table API is available through this add-on module, which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.
$ npm test
Logo created by Diego Pasquali
Read carefully our Code Of Conduct
Search on Google/Github
If you can’t find anything, open an issue
If you feel comfortable about fixing the issue, fork the repo
Commit to your local branch (which must be different from master)
Submit your Pull Request (be sure to include tests and update documentation)
The MIT License (MIT)
Copyright (c) 2010 – 2016 Charlie Robbins, Jarrett Cruger & the Contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
How to create a simple http proxy in node.js? - Stack Overflow

Datacenter proxies

  • HTTP & SOCKS
  • Price $1.3/IP
  • Locations: DE, RU, US
  • 5% OFF coupon: APFkysWLpG

Visit proxy6.net

How to create a simple http proxy in node.js? – Stack Overflow

I’m trying to create a proxy server to pass HTTP GET requests from a client to a third party website (say google). My proxy just needs to mirror incoming requests to their corresponding path on the target site, so if my client’s requested url is:
127. 0. 1/images/srpr/
The following resource should be served:
Here is what I came up with:
eateServer(onRequest)(80);
function onRequest (client_req, client_res) {
dListener(“end”, function() {
var options = {
hostname: ”,
port: 80,
path:,
method:
headers: client_req. headers};
var quest(options, function(res) {
var body;
(‘data’, function (chunk) {
body += chunk;});
(‘end’, function () {
client_res. writeHead(atusCode, res. headers);
(body);});});
();});}
It works well with html pages, but for other types of files, it just returns a blank page or some error message from target site (which varies in different sites).
asked Dec 3 ’13 at 12:47
Nasser TorabzadeNasser Torabzade6, 0548 gold badges26 silver badges36 bronze badges
1
I don’t think it’s a good idea to process response received from the 3rd party server. This will only increase your proxy server’s memory footprint. Further, it’s the reason why your code is not working.
Instead try passing the response through to the client. Consider following snippet:
var = require(”);
eateServer(onRequest)(3000);
function onRequest(client_req, client_res) {
(‘serve: ‘ +);
method:,
var proxy = quest(options, function (res) {
client_res. headers)
(client_res, {
end: true});});
(proxy, {
end: true});}
answered Dec 3 ’13 at 15:05
18
Here’s an implementation using node–proxy from nodejitsu.
var Proxy = require(‘-proxy’);
var proxy = eateProxyServer({});
eateServer(function(req, res) {
(req, res, { target: ”});})(3000);
answered Sep 21 ’15 at 21:12
bosgoodbosgood1, 79017 silver badges20 bronze badges
2
Here’s a proxy server using request that handles redirects. Use it by hitting your proxy URL your_url]
var url = require(‘url’);
var request = require(‘request’);
function onRequest(req, res) {
var queryData = (, true);
if () {
request({
url:})(‘error’, function(e) {
(e);})(res);}
else {
(“no url found”);}}
answered Dec 15 ’14 at 4:33
HenryHenry2, 1981 gold badge23 silver badges16 bronze badges
Super simple and readable, here’s how you create a local proxy server to a local HTTP server with just (tested on v8. 1. 0). I’ve found it particular useful for integration testing so here’s my share:
/**
* Once this is running open your browser and hit localhost
* You’ll see that the request hits the proxy and you get the HTML back
*/
‘use strict’;
const net = require(‘net’);
const = require(”);
const PROXY_PORT = 80;
const HTTP_SERVER_PORT = 8080;
let proxy = eateServer(socket => {
(‘data’, message => {
(‘—PROXY- got message’, String());
let serviceSocket = new ();
nnect(HTTP_SERVER_PORT, ‘localhost’, () => {
(‘—PROXY- Sending message to server’);
(message);});
(‘data’, data => {
(‘—PROXY- Receiving message from server’, String();
(data);});});});
let Server = eateServer((req, res) => {
switch () {
case ‘/’:
res. writeHead(200, {‘Content-Type’: ‘text/html’});
(‘

Ciao!

‘);
break;
default:
res. writeHead(404, {‘Content-Type’: ‘text/plain’});
(‘404 Not Found’);}});
(PROXY_PORT);
(HTTP_SERVER_PORT);
answered Jun 23 ’17 at 17:03
Francesco CasulaFrancesco Casula23. 5k12 gold badges124 silver badges128 bronze badges
Here’s a more optimized version of Mike’s answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url = and it will automatically set HTTP and HTTPS stuff without manually doing it.
var express = require(‘express’)
var app = express()
const { response} = require(‘express’);
(‘/’, function(clientRequest, clientResponse) {
var url;
url = ”
var parsedHost = (‘/’)(2)(0, 1)(‘/’)
var parsedPort;
var parsedSSL;
if (artsWith(”)) {
parsedPort = 443
parsedSSL =} else if (artsWith(”)) {
parsedPort = 80
parsedSSL =}
hostname: parsedHost,
port: parsedPort,
headers: {
‘User-Agent’: clientRequest. headers[‘user-agent’]}};
var serverRequest = quest(options, function(serverResponse) {
var body = ”;
if (String(serverResponse. headers[‘content-type’]). indexOf(‘text/html’)! == -1) {
(‘data’, function(chunk) {
(‘end’, function() {
// Make changes to HTML files when they’re done being read.
body = place(`example`, `Cat! `);
clientResponse. writeHead(atusCode, serverResponse. headers);
(body);});}
(clientResponse, {
end: true});
ntentType(serverResponse. headers[‘content-type’])}});
();});
(3000)
(‘Running on 0. 0:3000’)
answered Aug 26 ’20 at 17:39
Your code doesn’t work for binary files because they can’t be cast to strings in the data event handler. If you need to manipulate binary files you’ll need to use a buffer. Sorry, I do not have an example of using a buffer because in my case I needed to manipulate HTML files. I just check the content type and then for text/html files update them as needed:
(‘/*’, function(clientRequest, clientResponse) {
method: ‘GET’};
var googleRequest = quest(options, function(googleResponse) {
if (String(googleResponse. indexOf(‘text/html’)! == -1) {
body = place(/, host + ‘:’ + port);
body = place(
//,
‘);
clientResponse. writeHead(atusCode, googleResponse. headers);
end: true});}});
answered Dec 2 ’14 at 23:46
I juste wrote a proxy in nodejs that take care of HTTPS with optional decoding of the message.
This proxy also can add proxy-authentification header in order to go through a corporate proxy. You need to give as argument the url to find the file in order to configurate the usage of corporate proxy.
answered Oct 26 ’16 at 17:09
here is one that I made:
var = require(“”)
var Unblocker = require(“unblocker”)
var unblocker = Unblocker({})
eateServer(function(req, res){
unblocker(req, res, function(err){
var headers = {“content-type”: “text/html”}
if(err){
res. writeHead(500, headers)
return ( || err)}
if( == “/”){
res. writeHead(200, headers)
return (
`
Seventh Grade by Gary Soto

`)}else{
res. writeHead(404, headers)
return (“ERROR 404: File Not Found. “);}})})
(8080)
demo: view the demo:
answered Mar 9 at 16:07
Not the answer you’re looking for? Browse other questions tagged javascript proxy or ask your own question.
Create a Simple HTTP Proxy in Node.js - Mastering JS

Create a Simple HTTP Proxy in Node.js – Mastering JS

Oct 30, 2020
The -proxy package on npm is the most popular way to create an
HTTP proxy in Below is a standalone script that shows how to use -proxy with Express, and make a
proxied HTTP request using Axios.
const express = require(‘express’);
const Proxy = require(‘-proxy’);
// Create a proxy and listen on port 3000
const proxy = eateProxyServer({});
const app = express();
(‘*’, function(req, res) {
// Prints “Request GET
(‘Request’,, );
(req, res, { target: `${otocol}${name}`});});
const server = await (3000);
const axios = require(‘axios’);
const res = await (”, {
// `proxy` means the request actually goes to the server listening
// on localhost:3000, but the request says it is meant for
// ”
proxy: {
host: ‘localhost’,
port: 3000}});
();
The -proxy package doesn’t require you to use Express. You can also use Node’s built-in HTTPServer class:
const = require(”);
eateServer(function(req, res) {
(req, res, { target: `${otocol}${name}`});})(3000);
Modifying Requests
With a proxy server, there’s two HTTP requests: the inbound request that the proxy server received, and the outbound
request that the proxy server sends. In the previous examples, the inbound request is the same as the outbound request.
However, many proxy servers modify outbound requests. For example, you may want your proxy server to set an HTTP header.
In order to modify the outbound request, you need to listen to -proxy’s ‘proxyReq’ event, which gives you access to the outbound request that -proxy will send. For example, here’s how you can set the ‘Authorization’ header on all outbound requests:
(‘proxyReq’, function(proxyReq) {
tHeader(‘Authorization’, ‘my-secret-key’);});
More Node Tutorials
Convert HTML to Pug
Convert Pug to HTML
How to Install on Ubuntu
How to Check Your Version
HTTP Servers in
Websocket Server in
Using the Buffer `toString()` Function in

Frequently Asked Questions about node_js http proxy

How do I create a simple HTTP proxy in node JS?

Setup a basic stand-alone proxy server createProxyServer({target:’http://localhost:9000′}).listen(8000); // See (†) // // Create your target server // http. createServer(function (req, res) { res. writeHead(200, { ‘Content-Type’: ‘text/plain’ }); res. write(‘request successfully proxied!’

How can I use an HTTP proxy with node js HTTP client?

var http = require(“http”); var options = { host: “proxy”, port: 8080, path: “http://www.google.com”, headers: { Host: “www.google.com” } }; http. get(options, function(res) { console. log(res); res. pipe(process.Jan 22, 2014

What is a proxy in node JS?

In a nutshell, a proxy is an intermediary application which sits between two (or more) services and processes/modifies the requests and responses in both directions. …Aug 11, 2020

Leave a Reply

Your email address will not be published.