npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-square-better-http-proxy

v0.1.3

Published

http proxy middleware for koa

Downloads

22

Readme

koa-square-better-http-proxy

本项目 fork 自 https://github.com/nsimmons/koa-better-http-proxy ,以下为原项目 README

KoaJs Slack

Koa middleware to proxy request to another host and pass response back. Based on express-http-proxy.

Install

$ npm install koa-better-http-proxy --save

Usage

proxy(host, options);

To proxy URLS to the host 'www.google.com':

var proxy = require('koa-better-http-proxy');
var Koa = require('koa');

var app = new Koa();
app.use(proxy('www.google.com'));

If you wish to proxy only specific paths, you can use a router middleware to accomplish this. See Koa routing middlewares.

Options

agent

Use a custom http.Agent for proxy requests.

var agent = new http.Agent(options);
app.use(proxy('www.google.com', {
  agent: agent,
}));

port

The port to use for the proxied host.

app.use(proxy('www.google.com', {
  port: 443
}));

headers

Additional headers to send to the proxied host.

app.use(proxy('www.google.com', {
  headers: {
    'X-Special-Header': 'true'
  }
}));

strippedHeaders

Headers to remove from proxy response.

app.use(proxy('www.google.com', {
  strippedHeaders: [
    'set-cookie'
  ]
}));

preserveReqSession

Pass the session along to the proxied request

app.use(proxy('www.google.com', {
  preserveReqSession: true
}));

proxyReqPathResolver (supports Promises)

Provide a proxyReqPathResolver function if you'd like to operate on the path before issuing the proxy request. Use a Promise for async operations.

app.use(proxy('localhost:12345', {
  proxyReqPathResolver: function(ctx) {
    return require('url').parse(ctx.url).path;
  }
}));

Promise form

app.use(proxy('localhost:12345', {
  proxyReqPathResolver: function(ctx) {
    return new Promise(function (resolve, reject) {
      setTimeout(function () {   // do asyncness
        resolve(fancyResults);
      }, 200);
    });
  }
}));

filter

The filter option can be used to limit what requests are proxied. Return true to execute proxy.

For example, if you only want to proxy get request:

app.use(proxy('www.google.com', {
  filter: function(ctx) {
     return ctx.method === 'GET';
  }
}));

userResDecorator (supports Promise)

You can modify the proxy's response before sending it to the client.

exploiting references

The intent is that this be used to modify the proxy response data only.

Note: The other arguments (proxyRes, ctx) are passed by reference, so you can currently exploit this to modify either response's headers, for instance, but this is not a reliable interface. I expect to close this exploit in a future release, while providing an additional hook for mutating the userRes before sending.

userResHeadersDecorator (supports Promise)

You can modify the proxy's headers before sending it to the client.

gzip responses

If your proxy response is gzipped, this program will automatically unzip it before passing to your function, then zip it back up before piping it to the user response. There is currently no way to short-circuit this behavior.

app.use(proxy('www.google.com', {
  userResDecorator: function(proxyRes, proxyResData, ctx) {
    data = JSON.parse(proxyResData.toString('utf8'));
    data.newProperty = 'exciting data';
    return JSON.stringify(data);
  }
}));
app.use(proxy('httpbin.org', {
  userResDecorator: function(proxyRes, proxyResData) {
    return new Promise(function(resolve) {
      proxyResData.funkyMessage = 'oi io oo ii';
      setTimeout(function() {
        resolve(proxyResData);
      }, 200);
    });
  }
}));

limit

This sets the body size limit (default: 1mb). If the body size is larger than the specified (or default) limit, a 413 Request Entity Too Large error will be returned. See bytes.js for a list of supported formats.

app.use(proxy('www.google.com', {
  limit: '5mb'
}));

proxyReqOptDecorator (supports Promise form)

You can mutate the request options before sending the proxyRequest. proxyReqOpt represents the options argument passed to the (http|https).request module.

NOTE: req.path cannot be changed via this method; use proxyReqPathResolver instead.

app.use(proxy('www.google.com', {
  proxyReqOptDecorator: function(proxyReqOpts, ctx) {
    // you can update headers
    proxyReqOpts.headers['content-type'] = 'text/html';
    // you can change the method
    proxyReqOpts.method = 'GET';
    return proxyReqOpts;
  }
}));

You can use a Promise for async style.

app.use(proxy('www.google.com', {
  proxyReqOptDecorator: function(proxyReqOpts, ctx) {
    return new Promise(function(resolve, reject) {
      proxyReqOpts.headers['content-type'] = 'text/html';
      resolve(proxyReqOpts);
    })
  }
}));

proxyReqBodyDecorator (supports Promise form)

You can mutate the body content before sending the proxyRequest.

app.use(proxy('www.google.com', {
  proxyReqBodyDecorator: function(bodyContent, ctx) {
    return bodyContent.split('').reverse().join('');
  }
}));

You can use a Promise for async style.

app.use(proxy('www.google.com', {
  proxyReqBodyDecorator: function(proxyReq, ctx) {
    return new Promise(function(resolve, reject) {
      http.get('http://dev/null', function (err, res) {
        if (err) { reject(err); }
        resolve(res);
      });
    })
  }
}));

https

Normally, your proxy request will be made on the same protocol as the original request. If you'd like to force the proxy request to be https, use this option.

app.use(proxy('www.google.com', {
  https: true
}));

preserveHostHdr

You can copy the host HTTP header to the proxied express server using the preserveHostHdr option.

app.use(proxy('www.google.com', {
  preserveHostHdr: true
}));

parseReqBody

The parseReqBody option allows you to control parsing the request body. For example, disabling body parsing is useful for large uploads where it would be inefficient to hold the data in memory.

This defaults to true in order to preserve legacy behavior.

When false, no action will be taken on the body and accordingly req.body will no longer be set.

Note that setting this to false overrides reqAsBuffer and reqBodyEncoding below.

app.use(proxy('www.google.com', {
  parseReqBody: false
}));

reqAsBuffer

Note: this is an experimental feature. ymmv

The reqAsBuffer option allows you to ensure the req body is encoded as a Node Buffer when sending a proxied request. Any value for this is truthy.

This defaults to to false in order to preserve legacy behavior. Note that the value of reqBodyEnconding is used as the encoding when coercing strings (and stringified JSON) to Buffer.

Ignored if parseReqBody is set to false.

app.use(proxy('www.google.com', {
  reqAsBuffer: true
}));

reqBodyEncoding

Encoding used to decode request body. Defaults to utf-8.

Use null to preserve as Buffer when proxied request body is a Buffer. (e.g image upload) Accept any values supported by raw-body.

The same encoding is used in the userResDecorator method.

Ignored if parseReqBody is set to false.

app.use(proxy('httpbin.org', {
  reqBodyEncoding: null
}));

connectTimeout

By default, node does not express a timeout on connections. Use connectTimeout option to impose a specific timeout on the inital connection. (connect for http requests and secureConnect for https) This is useful if there are dns, network issues, or if you are uncertain if the destination is reachable. Timed-out requests will respond with 504 status code and a X-Timeout-Reason header.

app.use(proxy('httpbin.org', {
  connectTimeout: 2000  // in milliseconds, two seconds
}));

timeout

By default, node does not express a timeout on connections. Use timeout option to impose a specific timeout. This includes the time taken to make the connection and can be used with or without connectTimeout. Timed-out requests will respond with 504 status code and a X-Timeout-Reason header.

app.use(proxy('httpbin.org', {
  timeout: 2000  // in milliseconds, two seconds
}));