A full-featured http proxy for node.js

Overview

node-http-proxy Build Status codecov

node-http-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

npm install http-proxy --save

Back to top

Upgrading from 0.8.x ?

Click here

Back to top

Core Concept

A new proxy is created by calling createProxyServer and passing an options object as argument (valid properties are available here)

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

var proxy = httpProxy.createProxyServer(options); // See (†)

†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

http.createServer(function(req, res) {
  proxy.web(req, res, { target: 'http://mytarget.com:8080' });
});

Errors can be listened on either using the Event Emitter API

proxy.on('error', function(e) {
  ...
});

or using the callback API

proxy.web(req, res, { target: 'http://mytarget.com:8080' }, 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.

Back to top

Use Cases

Setup a basic stand-alone proxy server

var http = require('http'),
    httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.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!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.

Back to top

Setup a stand-alone proxy server with custom server logic

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 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);

Back to top

Setup a stand-alone proxy server with proxy request header re-writing

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 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);

Back to top

Modify a response from a proxied server

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.

Back to top

Setup a stand-alone proxy server with latency

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);

Back to top

Using HTTPS

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
//
// 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);
HTTPS -> HTTPS
//
// 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);
HTTP -> HTTPS (using a PKCS12 client certificate)
//
// 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);

Back to top

Proxying WebSockets

You can activate the websocket support for the proxy using ws:true in the options.

//
// Create a proxy server for websockets
//
httpProxy.createServer({
  target: 'ws://localhost:9014',
  ws: true
}).listen(8014);

Also you can proxy the websocket requests just calling the ws(req, socket, head) method.

//
// 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);

Back to top

Options

httpProxy.createProxyServer 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 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:

    '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

Back to top

Listening for proxy events

  • 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. It gives you a chance to alter the proxyReq request object. 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 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');
});

Back to top

Shutdown

  • 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 httpProxy.createProxyServer({
  target: {
    host: 'localhost',
    port: 1337
  }
});

proxy.close();

Back to top

Miscellaneous

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
    };
    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);

ProxyTable API

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.

Test

$ npm test

Logo

Logo created by Diego Pasquali

Back to top

Contributing and Issues

  • 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)

Back to top

License

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.

Comments
  • Changing headers should be an option

    Changing headers should be an option

    changing the headers "location" & "origin" when proxying websocket request should be an option, because this is important to make the proxying behave like "not happened".

    confirmed-bugs 
    opened by VanCoding 37
  • hanging POST requests

    hanging POST requests

    Hi, I'm using express and trying to proxy certain requests to a different server, as follows (simplified):

    var httpProxy = require('http-proxy');
    var apiProxy = new httpProxy.RoutingProxy();
    ...
    app.all('/api/*', function(req, res){
      apiProxy.proxyRequest(req, res, {host: 'example.com', port: 9000});
    });
    

    ...but POST requests to my server appear to just hang, and never arrive at the target server.

    I'm working on a stripped-down-but-working example of this but thought I'd ask first. Has anyone seen this behavior, or are there good examples of node-http-proxy coexisting with express? Thanks!

    faq 
    opened by joeyAghion 36
  • http-proxy doesn't proxy the latest websocket specifications

    http-proxy doesn't proxy the latest websocket specifications

    Howdy,

    A few days ago, we added FF6 and Chrome 14 websocket support to Socket.IO. But http-proxy doesn't seem to be able to proxy these upgrade events.

    If I run a plain Socket.IO 0.8.2 chat example it works fine in FF6 and latest chrome, but if I add node-http-proxy infront of it only the Draft 76 specification receives a upgrade event.

    After a bit digging I found out that https://github.com/nodejitsu/node-http-proxy/blob/master/lib/node-http-proxy.js#L862 doesn't get fired for the new websocket specifications (it does work for older websocket specifications like draft 76)

    confirmed-bugs 
    opened by 3rd-Eden 33
  • Don't send requests with Connection:keep-alive if we have no agent.

    Don't send requests with Connection:keep-alive if we have no agent.

    Avoids unhandleable ECONNRESETs.

    I think this is arguably a Node http bug (in 0.10.18 at least), but: if you run

    http.request({headers: {connection: 'keep-alive'}, agent: false});
    

    During the ClientRequest constructor, self.shouldKeepAlive is set to false because there is no agent. But then it calls (indirectly) the storeHeader function (in http.js, which sets self.shouldKeepAlive to true because you specified the keep-alive header.

    Then once the request is over responseOnEnd (in http.js) runs. Because shouldKeepAlive is true, we do NOT destroy the underlying socket. But we do remove its error listener. However, because we do NOT have an agent, nobody cares that we emit free, and the socket is essentially leaked.

    That is, we continue to have an open socket to the target server, which has no error listener and which will never be cleaned up.

    It's bad enough that this is a resource leak. But to make matters worse: let's say that the target server dies. This socket will emit an ECONNRESET error... and since there is no error listener on the socket (there's a listener on the ClientRequest! but not on the socket), bam, time for an incredibly confusing error to be thrown from the top level, probably crashing your process or triggering uncaughtException.

    I think the best workaround here is to ensure that if we have no agent, then we don't send connection: keep-alive. This PR is one implementation of this.

    (I'll work around this a different way in Meteor for now: by providing an explicit Agent.)

    opened by glasser 29
  • crash in accessing res.connection.pair

    crash in accessing res.connection.pair

    Hi,

    I am using the latest http-proxy in hostNameOnly mode and it kept crashing in https://github.com/nodejitsu/node-http-proxy/blob/master/lib/node-http-proxy.js#L372

    I dont' have the stack trace right now, but it said something like res.connection was undefined. . I just changed res to req in that line and everything started to work. I am very new to nodejs, so not sure what may be happening, but is this just a typo? I would think you would use the request object to set the header on the proxied request, so it does seem like one.

    Regards Qasim

    blocked-nodejs-core 
    opened by qzaidi 29
  • can't handle www.host

    can't handle www.host

    Suppose I wanted to proxy a site like cb2.com -- visiting this site, you'll see that it immediately redirects you to www.cb2.com. This is a problem, as I'm unable to proxy the content of the site as my browser begins accessing www.cb2.com directly instead of continuing to proxy via localhost.

    I've tried simply setting the host to be www.cb2.com instead of cb2.com, but it fails. No errors, the browser just waits.

        proxy.proxyRequest(req, res, {
            host: 'www.cb2.com',
            port: 80
        });
    
    low-priority needs-investigation 
    opened by jmonster 26
  • Prevent headers from being sent twice

    Prevent headers from being sent twice

    In some cases, when there is an error, the headers are sent twice which throws an exception. I was able to reproduce by doing this:

    $ nc localhost 1080 << EOF
    > GET / HTTP/1.1
    > Host: foobar
    >
    > EOF
    

    `foobar' is a valid proxied website. A proxy using node-http-proxy is running on localhost:1080.

    This produces the following error:

    http.js:708
        throw new Error('Can\'t set headers after they are sent.');
              ^
    Error: Can't set headers after they are sent.
        at ServerResponse.OutgoingMessage.setHeader (http.js:708:11)
        at /Users/shad/Dropbox/work/hipache/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:332:13
        at Array.forEach (native)
        at ClientRequest.<anonymous> (/Users/shad/Dropbox/work/hipache/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:328:35)
        at ClientRequest.g (events.js:175:14)
        at ClientRequest.EventEmitter.emit (events.js:95:17)
        at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1630:21)
        at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:119:23)
        at Socket.socketOnData [as ondata] (http.js:1528:20)
        at TCP.onread (net.js:495:27)
    

    The problem here is that netcat does not read anything. I tried with a script that reads the response and the error does not occur. The simple `if' statement I added prevents the bug to happen and everything then works normally.

    opened by samalba 24
  • Unix socket support

    Unix socket support

    So I wanted to use node-http-proxy to serve content from multiple apps running locally on unix sockets. I found out quick that this was not going to work:

    var proxyServer = httpProxy.createServer({
        router: {
            'localhost': '/tmp/myapp.sock'
        }
    });
    

    I spent the next 5 hours or so trying to figure out why. It turns out the problem was in this method:

    ProxyTable.prototype.getProxyLocation
    

    That method is always looking for a host and a port, because it does a split on the string. It could easily be modified to use a unix socket path, which is the first argument for the net.Server.listen method, the same as a port. The core lib simply checks if this value is a number or a string.

    So anyway, rather than modifying the code because I didn't want to monkey around in there just yet. The simple solution after 5 hours of trying to make this reverse proxy unix sockets was this:

    var proxyServer = httpProxy.createServer({
        router: {
            'localhost': ':/tmp/myapp.sock'
        }
    });
    

    That my friends, is one magical colon.

    Thanks again for this great and extremely useful module. Let me know what you think about all this, I can try to contribute.

    Jim

    feature-request 
    opened by jimisaacs 22
  • response.resume error: Cannot resume() closed Socket.

    response.resume error: Cannot resume() closed Socket.

    Hey,

    I'm having this sporadic message, I haven't dig too much into it, but it started to show up once I Implemented a file uploading feature using connect-form.

    Any ideas?

    medium-priority please-confirm-fixed 
    opened by c4milo 21
  • Cannot read property 'protocol' of undefined

    Cannot read property 'protocol' of undefined

    README has this example for custom application logic (for caronte tree):

        var http = require('http'),
            httpProxy = require('http-proxy');
    
        //
        // Create a proxy server with custom application logic
        //
        var proxy = httpProxy.createProxyServer({});
    
        var server = require('http').createServer(function(req, res) {
            proxy.web(req, res, { target: 'http://127.0.0.1:8001' });
        });
    
        console.log("listening on port 9000")
        server.listen(9000);
    

    I'm getting these errors:

    $ node test.js 
    listening on port 9000
    
    /opt/nor-web-proxy/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:103
        var proxyReq = (server.options.target.protocol === 'https:' ? https : http
                                             ^
    TypeError: Cannot read property 'protocol' of undefined
        at Array.stream [as 3] (/opt/nor-web-proxy/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:103:42)
        at ProxyServer.web (/opt/nor-web-proxy/node_modules/http-proxy/lib/http-proxy/index.js:76:21)
        at Server.<anonymous> (/opt/nor-web-proxy/test.js:10:9)
        at Server.EventEmitter.emit (events.js:98:17)
        at HTTPParser.parser.onIncoming (http.js:2076:12)
        at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
        at Socket.socket.ondata (http.js:1966:22)
        at TCP.onread (net.js:525:27)
    

    I am running node v0.10.20.

    opened by thejhh 20
  • Websocket proxy does not complete

    Websocket proxy does not complete

    I am using http-proxy to proxy to the socket.io driven app tty.js

    The socket does not seem to be connecting most of the time. 1 of 5 times I refresh the page it connects, otherwise I see Text Status: Pending for the websocket, in chrome developer tools:

    I am using:

    • Amazon EC2 linux: $uname -a Linux ip-10-236-133-58 3.4.37-40.44.amzn1.x86_64 #1 SMP Thu Mar 21 01:17:08 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
    • Either node v0.10.13 and node v0.6.21
    • [email protected]
    opened by srossross 19
  • When i use the vite (bottom layer is node-http-proxy) to start a http-server and proxy the request to target server, ETIMEDOUT problem occurs frequently.

    When i use the vite (bottom layer is node-http-proxy) to start a http-server and proxy the request to target server, ETIMEDOUT problem occurs frequently.

    In vite, I was trying to start a http server with following code

    server: {
        open: true,
        proxy: setupProxy()
      }
    
    const setupProxy = () => {
      const backendAddr = 'http://192.168.50.213:8180/'
    
      const wsOptions = {
        target: backendAddr,
        ws: true
      }
      const httpOptions = {
        target: backendAddr,
        changeOrigin: true
      }
      return {
        '/stomp': wsOptions,
        '/api': httpOptions,
        '/pub': httpOptions,
        '/docs': httpOptions
      }
    }
    

    According to the vite document, Its bottom layer uses node-http-proxy. My problem is that my target server is sure to be accessible, but it will encounter proxy timeout problems from time to time.

    Error: connect ETIMEDOUT 192.168.50.213:8180
        at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16)
    3:23:48 PM [vite] http proxy error at /stomp/info?t=1670657002883:
    Error: connect ETIMEDOUT 192.168.50.213:8180
        at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16)
    3:23:48 PM [vite] http proxy error at /stomp/info?t=1670657002882:
    Error: connect ETIMEDOUT 192.168.50.213:8180
        at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16)
    3:23:48 PM [vite] http proxy error at /api/settings/hiddenMenuPaths:
    Error: connect ETIMEDOUT 192.168.50.213:8180
    

    What I can offer is that this problem will not occur when my target server deploys on a ssd, which is, the access speed is very fast. When I deploy the server on a hdd or when the network environment is more complicated, which is, the access speed is not so fast, but definitely not slow, problem returns. All my colleagues who use Mac have this problem, but all my colleagues who use Windows don't. Based on the above phenomenon, I doubt whether there are some special configurations for the mac version of nodejs, such as the default timeout time, fault tolerance or automatic retry mechanism, which causes frequent timeout problems when the target server apis are slightly slower.

    opened by TinyStorm 0
  • Serious pitfall: If Upstream doesn't respond in time, but does respond again after a while, Proxy will never work because the 'socket hangs up' has destroyed httpagent....

    Serious pitfall: If Upstream doesn't respond in time, but does respond again after a while, Proxy will never work because the 'socket hangs up' has destroyed httpagent....

    Serious pitfall: If Upstream doesn't respond in time, but does respond again after a while, Proxy will never work because the 'socket hangs up' has destoryed httpagent....

    opened by introspection3 1
  • [dist] Update dependency minimatch to 3.0.5 [SECURITY]

    [dist] Update dependency minimatch to 3.0.5 [SECURITY]

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | |---|---| | minimatch | 3.0.4 -> 3.0.5 |

    GitHub Vulnerability Alerts

    CVE-2022-3517

    A vulnerability was found in the minimatch package. This flaw allows a Regular Expression Denial of Service (ReDoS) when calling the braceExpand function with specific arguments, resulting in a Denial of Service.


    Configuration

    📅 Schedule: Branch creation - "" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    🔕 Ignore: Close this PR and you won't be reminded about this update again.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
  • How to get https API response body on proxyRes

    How to get https API response body on proxyRes

    Hello all!

    I have an http and an https API.

    When I use http API, when user login successfully I get access token on proxyRes and I add HttpOnly Cookie. This is working.

    But when I use https API I can't get response body. In my opinion because the response body is encrypted.

    How can I solution this problem. Is there a solution?

    This my code snippet;

    function interceptLoginResponse(proxyRes, req, res) {
                // Read the API's response body from 
                let apiResponseBody = ''
                proxyRes.on('data', (chunk) => {
                    chunk = chunk.toString('utf-8');
                    apiResponseBody += chunk
                })
    
    
                proxyRes.on('end', async () => {
                    try {
                        // Extract the authToken from API's response:
                        const {access_token} = await JSON.parse(apiResponseBody);
                
                        const cookies = new Cookies(req, res, {secure: true})
    
                        await cookies.set('access_token', access_token, { secure:true, pat:"/", httpOnly: true, sameSite: 'Strict', expirationDate:"21 Oct 2022 07:28:00 GMT"})
                        await res.status(200).json({ success: true })
                    } catch (err) {
                        reject(err)
                    }
                })
            }
    
    opened by guvensen 0
  • NodeJs giving me error when trying to start

    NodeJs giving me error when trying to start

    Helo, When im trying to start my server by doing httpProxy.createProxyServer(), im just getting the error TypeError: httpProxy.createProxyServer is not a function I have the http-proxy-module installed (npm I http-proxy), so that probably is not the issues

    http-proxy version: 1.18.1 nodejs version: v18.10.0

    Code:

    import * as http from "http";
    import * as fs from "fs";
    import * as path from "path";
    import * as httpProxy from "http-proxy";
    
    // Create a proxy server
    const proxy = httpProxy.createProxyServer({
          target: "https://discord.gg"
    }).listen(80);
    
    opened by DNAScanner 0
Releases(1.17.0)
  • 1.17.0(Apr 20, 2018)

    Due to some great contributions I'm happy to announce a new release of http-proxy containing numerous bug fixes, feature additions and documentation improvements. Thanks to all who contributed for their patience and willingness to contribute despite perceived stagnation in activity in the project. I welcome all contributions and those who are interested in getting more involved with the project. Below I will highlight the changes that landed in the latest version but you can find the full diff of the changes in https://github.com/nodejitsu/node-http-proxy/pull/1251

    • Add option to rewrite path of set-cookie headers. @swillis12
    • Add option for overriding http METHOD when proxying request @AydinChavez
    • Feature: selfHandleResponse for taking responsibility in returning your own response when listening on the proxyRes event. @cpd0101 @guoxiangyang
    • Add followRedirects option @n30n0v
    • Document timeout option @jlaamanen
    • Fix documentation typos @carpsareokiguess
    • Document buffer option @jonhunter1977
    • Include websocket non-upgrade response instead of just closing the socket. Allows auth schemes to be possible with websocket proxying. @Tigge
    • Stop using the writeHead method explicitly and let node handle it internally to prevent thrown errors @jakefurler
    • Be more defensive in handling of detecting response state when proxying @thiagobustamante
    Source code(tar.gz)
    Source code(zip)
Owner
http ... PARTY!
Who says networking can't be fun?
http ... PARTY!
The official proxy of Titanium Network with enhanced support for a large majority of sites with hCAPTCHA support. Successor to Alloy Proxy.

Corrosion Titanium Networks main web proxy. Successor to Alloy Installation: npm i corrosion Example: const Corrosion = require('corrosion'); const p

Titanium Network 79 Dec 21, 2022
Node.js web server framework for Http/1.1 or Http/2

Node.js web server framework for Http/1.1 or Http/2 Description: This is http framework, you can use it to create Http/1.1 or Http/2 service。 Now let'

Jeremy Yu 10 Mar 24, 2022
Global HTTP/HTTPS proxy agent configurable using environment variables.

global-agent Global HTTP/HTTPS proxy configurable using environment variables. Usage Setup proxy using global-agent/bootstrap Setup proxy using bootst

Gajus Kuizinas 267 Dec 20, 2022
A fully-featured Node.js REST client built for ease-of-use and resilience

flashheart A fully-featured Node.js REST client built for ease-of-use and resilience flashheart is built on http-transport to provide everything you n

BBC 118 Jun 21, 2022
Highly sophisticated proxy used for evading internet censorship or accessing websites in a controlled sandbox using the power of service-workers and more! Easy deployment version (Node.js)

Ultraviolet-Node The deployable version of Ultraviolet, a highly sophisticated proxy used for evading internet censorship or accessing websites in a c

Titanium Network 27 Jan 2, 2023
Highly sophisticated proxy used for evading internet censorship or accessing websites in a controlled sandbox using the power of service-workers and more! Easy deployment version (Node.js)

Ultraviolet-Node The deployable version of Ultraviolet, a highly sophisticated proxy used for evading internet censorship or accessing websites in a c

Titanium Network 34 Apr 15, 2022
Promise based HTTP client for the browser and node.js

axios Promise based HTTP client for the browser and node.js New axios docs website: click here Table of Contents Features Browser Support Installing E

axios 98k Dec 31, 2022
Ajax for Node.js and browsers (JS HTTP client)

superagent Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features T

Sloth 16.2k Jan 1, 2023
HTTP server mocking and expectations library for Node.js

Nock HTTP server mocking and expectations library for Node.js Nock can be used to test modules that perform HTTP requests in isolation. For instance,

Nock 11.9k Jan 3, 2023
🌐 Human-friendly and powerful HTTP request library for Node.js

Sindre's open source work is supported by the community. Special thanks to: Human-friendly and powerful HTTP request library for Node.js Moving from R

Sindre Sorhus 12.5k Jan 9, 2023
Simplifies node HTTP request making.

Requestify - Simplifies node HTTP request making. Requestify is a super easy to use and extendable HTTP client for nodeJS + it supports cache (-:. Ins

Ran Mizrahi 222 Nov 28, 2022
Run HTTP over UDP with Node.js

nodejs-httpp - Run HTTP over UDP based transport and Bring Web in Peer or P2P styles main js modules: udt.js, httpp.js, udts.js and httpps.js, that's

AppNet.Link 142 Aug 2, 2022
Very very very powerful, extensible http client for both node.js and browser.

ES-Fetch-API 中文 | English Very very very powerful, extensible http client for both node.js and browser. Why should you use ES-Fetch API? Still using a

null 17 Dec 12, 2022
A proxy web app that serves ABC iView content outside of the iView webplayer, avoiding intrusive data harvesting.

iview-proxy A proxy web app that serves ABC iView content outside of the iView webplayer, avoiding intrusive data harvesting. There's also a cool Andr

The OpenGov Australia Project 11 Jul 16, 2022
DSC-AlarmServer - Creates web interface to DSC/Envisalink with proxy.

DSC-AlarmServer Creates web interface to DSC/Envisalink with proxy. Since the Envisalink module can only have one connection, this phython script can

null 4 Oct 11, 2022
Simple proxy that is intended to support on chaos testing.

Proxy with Behavior Proxy with Behavior is a node application that work as a reverse proxy, and enables apply some behaviors to be executed in request

José Carlos de Moraes Filho 7 Jan 28, 2022
Prefect API Authentication/Authorization Proxy for on-premises deployments

Proxy Authorization Service for Prefect UI and Prefect CLI Prefect is a great platform for building data flows/pipelines. It supports hybrid execution

Softrams 20 Dec 10, 2022
wabac.js CORS Proxy

wabac.js CORS Proxy This provides a simple CORS proxy, which is designed to run as a Cloudflare Worker. This system is compatible with wabac.js-based

Webrecorder 3 Mar 8, 2022
Simple, configurable part mock part proxy

Moxy Simple, configurable mock / proxy server. Table of Contents Quick start Programatic CLI Docker Docker compose Usage Programatic Via HTTP requests

Acrontum GmbH 7 Aug 12, 2022