### Simple HTTP Benchmark Setup Source: https://github.com/http-party/node-http-proxy/blob/master/benchmark/README.md Instructions for setting up a simple HTTP benchmark using node-http-proxy. This involves running a proxy server, a target server, and a wrk process concurrently. ```javascript node benchmark/scripts/proxy.js ``` ```javascript node benchmark/scripts/hello.js ``` ```bash wrk -c 20 -d5m -t 2 http://127.0.0.1:8000 ``` -------------------------------- ### Listening for Connections Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Wraps the proxy instance in a web server and starts listening on the specified port. This function is used for convenience to create a standalone proxy server. ```javascript proxy.listen(port); ``` -------------------------------- ### Routing Proxy Configuration with http-proxy Source: https://github.com/http-party/node-http-proxy/wiki/Routing-proxy-with-access-logging This JavaScript code snippet demonstrates how to configure and run a routing proxy using the node-http-proxy library. It sets up routing rules to direct incoming requests to different backend applications based on URL patterns. The proxy listens on port 3000 and logs requests before forwarding them. ```javascript var httpProxy = require('http-proxy'); var options = { router: { '/page1$' : 'localhost:3010', '/page2$' : 'localhost:3020', // default route '.*' : 'localhost:3020' }}; var router = new httpProxy.RoutingProxy(options); var proxy = httpProxy.createServer(function(req,res) { console.log("request: " + req.path + "; method: " + req.method); router.proxyRequest(req,res); }); proxy.listen(3000, function() { console.log("Routing proxy listening on " + proxy.address().port); }); ``` -------------------------------- ### Basic Standalone Proxy Server Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Sets up a basic standalone proxy server that forwards requests to a target server running on port 9000 and listens on port 8000. It also includes an example of a target server. ```javascript var http = require('http'), httpProxy = require('http-proxy'); httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†) http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(9000); ``` -------------------------------- ### ProxyServer API Source: https://github.com/http-party/node-http-proxy/blob/master/README.md The ProxyServer object returned by `createProxyServer` has the following methods: * `web(req, res, [options], [callback])`: Proxies regular HTTP(S) requests. * `ws(req, socket, head, [options])`: Proxies WS(S) requests. * `listen(port)`: Wraps the proxy in a webserver and starts listening. * `close([callback])`: Closes the inner webserver. ```APIDOC ProxyServer: createProxyServer(options) options: Object - Configuration options for the proxy. Returns: ProxyServer instance web(req, res, [options], [callback]) req: http.IncomingMessage - The request object. res: http.ServerResponse - The response object. options: Object - Optional target and other proxy settings. callback: Function - Optional error handling callback. ws(req, socket, head, [options]) req: http.IncomingMessage - The request object. socket: net.Socket - The socket object. head: Buffer - The head buffer. options: Object - Optional target and other proxy settings. listen(port) port: Number - The port to listen on. close([callback]) callback: Function - Optional callback after closing. ``` -------------------------------- ### Shutting Down the Proxy Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Provides an example of how to close the http-proxy server, which stops it from accepting new connections. This is useful when running the server within another program or for testing purposes. ```js var proxy = new httpProxy.createProxyServer({ target: { host: 'localhost', port: 1337 } }); proxy.close(); ``` -------------------------------- ### wrk Usage Source: https://github.com/http-party/node-http-proxy/blob/master/benchmark/README.md Displays the usage instructions for the wrk benchmarking tool, outlining available options for configuring tests such as connections, duration, threads, and scripting. ```bash $ wrk Usage: wrk Options: -c, --connections Connections to keep open -d, --duration Duration of test -t, --threads Number of threads to use -s, --script Load Lua script file -H, --header Add header to request --latency Print latency statistics --timeout Socket/request timeout -v, --version Print version details Numeric arguments may include a SI unit (1k, 1M, 1G) Time arguments may include a time unit (2s, 2m, 2h) ``` -------------------------------- ### Proxy Web and WebSocket Requests Source: https://github.com/http-party/node-http-proxy/blob/master/UPGRADING.md Demonstrates how to proxy both standard HTTP requests using `.web()` and WebSocket requests using `.ws()`. It sets up a proxy server and listens for the 'upgrade' event to handle WebSocket traffic. ```javascript var proxy = new httpProxy.createProxyServer({ target: { host: 'localhost', port: 9015 } }); var proxyServer = http.createServer(function (req, res) { proxy.web(req, res); }); // // Listen to the `upgrade` event and proxy the // WebSocket requests as well. // proxyServer.on('upgrade', function (req, socket, head) { proxy.ws(req, socket, head); }); ``` -------------------------------- ### Listening for Proxy Events Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Demonstrates how to listen for various events emitted by the http-proxy server, including 'error', 'proxyRes', 'open', and 'close'. It shows how to handle errors, log responses, and manage WebSocket connections. ```js var httpProxy = require('http-proxy'); // Error example // // Http Proxy Server with bad target // var proxy = httpProxy.createServer({ target:'http://localhost:9005' }); proxy.listen(8005); // // Listen for the `error` event on `proxy`. proxy.on('error', function (err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Something went wrong. And we are reporting a custom error message.'); }); // // Listen for the `proxyRes` event on `proxy`. // proxy.on('proxyRes', function (proxyRes, req, res) { console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2)); }); // // Listen for the `open` event on `proxy`. // proxy.on('open', function (proxySocket) { // listen for messages coming FROM the target here proxySocket.on('data', hybiParseAndLogMessage); }); // // Listen for the `close` event on `proxy`. // proxy.on('close', function (res, socket, head) { // view disconnected websocket connections console.log('Client disconnected'); }); ``` -------------------------------- ### Create HTTP Proxy Server Source: https://github.com/http-party/node-http-proxy/blob/master/UPGRADING.md Creates an HTTP proxy server with a specified target. The server listens on a given port. ```javascript httpProxy.createServer({ target:'http://localhost:9003' }).listen(8003); ``` -------------------------------- ### Proxy Request with Custom Server Logic Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Sets up a standalone proxy server that handles incoming requests with custom server logic before forwarding them to a target. It uses `httpProxy.createProxyServer()` and `proxy.web()` to manage the proxying. Dependencies include the built-in 'http' module and the 'http-proxy' library. ```js var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with custom application logic // var proxy = httpProxy.createProxyServer({}); // // Create your custom server and just call `proxy.web()` to proxy // a web request to the target passed in the options // also you can use `proxy.ws()` to proxy a websockets request // var server = http.createServer(function(req, res) { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { target: 'http://127.0.0.1:5050' }); }); console.log("listening on port 5050") server.listen(5050); ``` -------------------------------- ### Proxy Server with Latency Simulation Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Sets up a proxy server that simulates a delay before forwarding requests to the target. This is achieved using `setTimeout` within the `http.createServer` callback. It also includes a basic target server to receive proxied requests. ```js var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with latency // var proxy = httpProxy.createProxyServer(); // // Create your server that makes an operation that waits a while // and then proxies the request // http.createServer(function (req, res) { // This simulates an operation that takes 500ms to execute setTimeout(function () { proxy.web(req, res, { target: 'http://localhost:9008' }); }, 500); }).listen(8008); // // Create your target server // http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(9008); ``` -------------------------------- ### Create Proxy Server Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Creates a new proxy server instance. The returned object has methods for proxying web and WebSocket requests, listening on a port, and closing the server. Options can be passed to configure the proxy. ```javascript var httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer(options); // See (†) ``` -------------------------------- ### httpProxy.createProxyServer Options Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Configuration options for creating a proxy server with http-proxy. These options control the behavior of the proxy, including target URL, WebSocket support, header modifications, and response handling. ```APIDOC httpProxy.createProxyServer(options) 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 http(s).request (see Node's https agent and http agent objects) - ssl: object to be passed to https.createServer() - 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 'http' or 'https'. Default: null. - cookieDomainRewrite: rewrites domain of `set-cookie` headers. Possible values: - false (default): disable cookie rewriting - String: new domain, for example `cookieDomainRewrite: "new.domain"`. 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: { "unchanged.domain": "unchanged.domain", "old.domain": "new.domain", "*": "" } ``` - cookiePathRewrite: rewrites path of `set-cookie` headers. Possible values: - false (default): disable cookie rewriting - 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: { "/unchanged.path/": "/unchanged.path/", "/old.path/": "/new.path/", "*": "" } ``` - 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: ```javascript 'use strict'; const streamify = require('stream-array'); const HttpProxy = require('http-proxy'); const proxy = new HttpProxy(); module.exports = (req, res, next) => { proxy.web(req, res, { target: 'http://localhost:4003/', buffer: streamify(req.rawBody) }, next); }; ``` NOTE: `options.ws` and `options.ssl` are optional. `options.target` and `options.forward` cannot both be missing If you are using the `proxyServer.listen` method, the following options are also applicable: * `ssl`: object to be passed to https.createServer() * `ws`: true/false, if you want to proxy websockets ``` -------------------------------- ### Create Proxy Server with HTTPS Target Source: https://github.com/http-party/node-http-proxy/blob/master/UPGRADING.md Creates a proxy server targeting an HTTPS URL. It allows specifying custom headers and uses the global HTTPS agent. ```javascript // // Create a HTTP Proxy server with a HTTPS target // httpProxy.createProxyServer({ target: 'https://google.com', agent : https.globalAgent, headers: { host: 'google.com' } }).listen(8011); ``` -------------------------------- ### HTTPS Proxy: HTTPS to HTTPS Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Sets up a proxy server for HTTPS to HTTPS communication. It requires SSL certificates for the proxy server and optionally enables certificate validation for the target connection using `secure: true`. This is useful for securing traffic between the proxy and the backend. ```js // // Create the proxy server listening on port 443 // httpProxy.createServer({ ssl: { key: fs.readFileSync('valid-ssl-key.pem', 'utf8'), cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8') }, target: 'https://localhost:9010', secure: true // Depends on your needs, could be false. }).listen(443); ``` -------------------------------- ### Create WebSocket Proxy Server Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Creates a proxy server specifically for WebSocket connections by setting the `ws: true` option in the createServer configuration. ```js // // Create a proxy server for websockets // httpProxy.createServer({ target: 'ws://localhost:9014', ws: true }).listen(8014); ``` -------------------------------- ### HTTPS Proxy: HTTPS to HTTP Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Configures a proxy server to handle HTTPS connections and forward them to an HTTP target. It requires SSL certificate and key files for the proxy server itself. The `ssl` option is used to provide these credentials. ```js // // Create the HTTPS proxy server in front of a HTTP server // httpProxy.createServer({ target: { host: 'localhost', port: 9009 }, ssl: { key: fs.readFileSync('valid-ssl-key.pem', 'utf8'), cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8') } }).listen(8009); ``` -------------------------------- ### Proxy WebSocket Requests Manually Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Demonstrates how to proxy WebSocket requests by listening for the 'upgrade' event on an HTTP server and using the `proxy.ws()` method. This allows for more granular control over WebSocket proxying. ```js // // Setup our server to proxy standard HTTP requests // var proxy = new httpProxy.createProxyServer({ target: { host: 'localhost', port: 9015 } }); var proxyServer = http.createServer(function (req, res) { proxy.web(req, res); }); // // Listen to the `upgrade` event and proxy the // WebSocket requests as well. // proxyServer.on('upgrade', function (req, socket, head) { proxy.ws(req, socket, head); }); proxyServer.listen(8015); ``` -------------------------------- ### Error Handling for Proxy Server Source: https://github.com/http-party/node-http-proxy/blob/master/UPGRADING.md Illustrates how to handle errors that occur during proxying. It listens for the 'error' event on the proxy server and provides a custom error response to the client. ```javascript var proxy = httpProxy.createServer({ target:'http://localhost:9005' }); // // Tell the proxy to listen on port 8005 // proxy.listen(8005); // // Listen for the `error` event on `proxy`. proxy.on('error', function (err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Something went wrong. And we are reporting a custom error message.'); }); ``` -------------------------------- ### HTTPS Proxy: HTTP to HTTPS with Client Certificate Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Configures an HTTP proxy server to connect to an HTTPS target that requires client certificate authentication. It uses the `pfx` and `passphrase` options within the `target` configuration to provide the client certificate details. ```js // // Create an HTTP proxy server with an HTTPS target // httpProxy.createProxyServer({ target: { protocol: 'https:', host: 'my-domain-name', port: 443, pfx: fs.readFileSync('path/to/certificate.p12'), passphrase: 'password', }, changeOrigin: true, }).listen(8000); ``` -------------------------------- ### Proxy Request with Header Rewriting Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Demonstrates how to proxy requests while modifying outgoing proxy request headers. It utilizes the 'proxyReq' event listener on the proxy server to add custom headers like 'X-Special-Proxy-Header'. This is useful for adding authentication or tracking information. ```js var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with custom application logic // var proxy = httpProxy.createProxyServer({}); // To modify the proxy connection before data is sent, you can listen // for the 'proxyReq' event. When the event is fired, you will receive // the following arguments: (http.ClientRequest proxyReq, http.IncomingMessage req, // http.ServerResponse res, Object options). This mechanism is useful when // you need to modify the proxy request before the proxy connection // is made to the target. // proxy.on('proxyReq', function(proxyReq, req, res, options) { proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); }); var server = http.createServer(function(req, res) { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { target: 'http://127.0.0.1:5050' }); }); console.log("listening on port 5050") server.listen(5050); ``` -------------------------------- ### Error Handling Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Listens for errors that occur during the proxying process. Errors can be handled using the Event Emitter API or a callback function passed to the proxy methods. ```javascript proxy.on('error', function(e) { ... }); ``` -------------------------------- ### Proxying HTTP Requests Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Proxies regular HTTP(S) requests to a specified target. This method can optionally accept a callback function to handle errors. ```javascript http.createServer(function(req, res) { proxy.web(req, res, { target: 'http://mytarget.com:8080' }); }); proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... }); ``` -------------------------------- ### Proxying WebSocket Requests Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Proxies WebSocket(S) requests. This method is used for handling real-time, bidirectional communication. ```javascript proxy.ws(req, socket, head, { target: 'ws://mytarget.com:8080' }); ``` -------------------------------- ### Modifying Proxy Response Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Demonstrates how to use the `selfHandleResponse` option to intercept and modify the response from the proxied server. This allows you to read the response body and send a custom response to the client. ```js var option = { target: target, selfHandleResponse : true }; proxy.on('proxyRes', function (proxyRes, req, res) { var body = []; proxyRes.on('data', function (chunk) { body.push(chunk); }); proxyRes.on('end', function () { body = Buffer.concat(body).toString(); console.log("res from proxied server:", body); res.end("my response to cli"); }); }); proxy.web(req, res, option); ``` -------------------------------- ### Closing the Server Source: https://github.com/http-party/node-http-proxy/blob/master/README.md Closes the inner web server created by the proxy instance, stopping it from listening on the given port. An optional callback can be provided to execute after the server is closed. ```javascript proxy.close([callback]); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.