@2o3t/koa2-proxy-middleware 中文文档教程

发布于 5年前 浏览 21 项目主页 更新于 3年前

@2o3t/koa2-proxy-middleware

Node.js 代理变得简单。 轻松为 koa2 配置代理中间件。

http-proxy-middleware 提供支持。 GitHub stars

TL;DR

代理 /api 请求到 http://www.2o3t.cn

const Koa = require('koa');
const app = new Koa();
const proxy = require('@2o3t/koa2-proxy-middleware');

// app.use(proxy({ target: 'http://www.2o3t.cn', changeOrigin: true }));

const Router = require('koa-router');
const router = new Router();
router.use(
  '/api',
  proxy({ target: 'http://www.2o3t.cn', changeOrigin: true })
);
app.use(router.routes())
  .use(router.allowedMethods());
app.listen(3000);
// http://localhost:3000/api/foo/bar -> http://www.2o3t.cn/api/foo/bar

All http-proxy options 可以一起使用带有一些额外的 http-proxy-middleware 选项

:bulb: 提示基于名称的虚拟托管站点

Install

$ npm install --save-dev @2o3t/koa2-proxy-middleware
// or
yarn add @2o3t/koa2-proxy-middleware

Core concept

代理中间件配置。

proxy([context,] config)

const proxy = require('@2o3t/koa2-proxy-middleware');

const apiProxy = proxy('/api', { target: 'http://www.2o3t.cn' });
//                   \____/   \_____________________________/
//                     |                    |
//                   context             options

// 'apiProxy' is now ready to be used as middleware in a server.
  • context: Determine which requests should be proxied to the target host. (more on context matching)
  • options.target: target host to proxy to. (protocol + host)

http-proxy-middleware 配置选项的完整列表

proxy(uri [, config])

// shorthand syntax for the example above:
const apiProxy = proxy('http://www.2o3t.cn/api');

关于速记配置的更多信息.

Example

koa2 服务器示例。

const Koa = require('koa');
const app = new Koa();
const proxy = require('@2o3t/koa2-proxy-middleware');

// proxy middleware options
const options = {
  target: 'http://www.2o3t.cn', // target host
  changeOrigin: true, // needed for virtual hosted sites
  ws: true, // proxy websockets
  pathRewrite: {
    '^/api/old-path': '/api/new-path', // rewrite path
    '^/api/remove/path': '/path' // remove base path
  },
  router: {
    // when request.headers.host == 'dev.localhost:3000',
    // override target 'http://www.2o3t.cn' to 'http://localhost:8000'
    'dev.localhost:3000': 'http://localhost:8000'
  }
};

// create the proxy (without context)
const exampleProxy = proxy(options);

app.use(exampleProxy)

app.use(ctx => {
    console.log(ctx.status);
});

app.listen(3003);

Context matching

提供一种替代方式来决定应该代理哪些请求; 如果您无法使用服务器的path parameter 来安装代理或当您需要更大的灵活性时。

RFC 3986 path 用于上下文匹配。

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment
  • 路径匹配

  • proxy({...}) - 匹配任何路径,所有请求都将被代理。

  • proxy('/', {...}) - 匹配任何路径,所有请求都将被代理。

  • proxy('/api', {...}) - 匹配以 /api 开头的路径

  • 多路径匹配

  • proxy([ '/api', '/ajax', '/someotherpath'], {...})

  • 通配符路径匹配

    对于细粒度控制,您可以使用通配符匹配。 全局模式匹配由 micromatch 完成。 访问 micromatchglob 获取更多通配示例。

  • proxy('**', {...}) 匹配任何路径,所有请求都将被代理。

  • proxy('**/*.html', {...}) 匹配任何以 .html 结尾的路径

  • proxy('/*.html' , {...}) 匹配直接在绝对路径下的路径

  • proxy('/api/**/*.html', {...}) 匹配以 < 结尾的请求/api 路径下的code>.html

  • proxy(['/api/**', '/ajax/**'], {...}) 组合多个模式

  • proxy(['/api/**', '!**/bad.json'], {...}) exclusion

    Note:在多路径匹配中,不能同时使用字符串路径和通配符路径。

  • 自定义匹配

    为了完全控制,您可以提供自定义函数来确定哪些请求应该被代理或不被代理。

  /**
   * @return {Boolean}
   */
  const filter = function(pathname, req) {
    return pathname.match('^/api') && req.method === 'GET';
  };

  const apiProxy = proxy(filter, { target: 'http://www.2o3t.cn' });

Options

http-proxy-middleware configuration options

new options

  • option.proxyBody: [Boolean|Function] Collect the results returned by the agent and assign them to ctx.body. Default: false.
option.proxyBody: true,
// or
option.proxyBody: function(json, proxyRes, req, res, ctx) {
    ctx.body = json;
}

License

麻省理工学院许可证 (MIT)

Copyright (c) 2018-2019 Zyao89

@2o3t/koa2-proxy-middleware

Node.js proxying made simple. Configure proxy middleware with ease for koa2.

Powered by http-proxy-middleware. GitHub stars

TL;DR

Proxy /api requests to http://www.2o3t.cn

const Koa = require('koa');
const app = new Koa();
const proxy = require('@2o3t/koa2-proxy-middleware');

// app.use(proxy({ target: 'http://www.2o3t.cn', changeOrigin: true }));

const Router = require('koa-router');
const router = new Router();
router.use(
  '/api',
  proxy({ target: 'http://www.2o3t.cn', changeOrigin: true })
);
app.use(router.routes())
  .use(router.allowedMethods());
app.listen(3000);
// http://localhost:3000/api/foo/bar -> http://www.2o3t.cn/api/foo/bar

All http-proxy options can be used, along with some extra http-proxy-middleware options.

:bulb: Tip: Set the option changeOrigin to true for name-based virtual hosted sites.

Install

$ npm install --save-dev @2o3t/koa2-proxy-middleware
// or
yarn add @2o3t/koa2-proxy-middleware

Core concept

Proxy middleware configuration.

proxy([context,] config)

const proxy = require('@2o3t/koa2-proxy-middleware');

const apiProxy = proxy('/api', { target: 'http://www.2o3t.cn' });
//                   \____/   \_____________________________/
//                     |                    |
//                   context             options

// 'apiProxy' is now ready to be used as middleware in a server.
  • context: Determine which requests should be proxied to the target host. (more on context matching)
  • options.target: target host to proxy to. (protocol + host)

(full list of http-proxy-middleware configuration options)

proxy(uri [, config])

// shorthand syntax for the example above:
const apiProxy = proxy('http://www.2o3t.cn/api');

More about the shorthand configuration.

Example

An example with koa2 server.

const Koa = require('koa');
const app = new Koa();
const proxy = require('@2o3t/koa2-proxy-middleware');

// proxy middleware options
const options = {
  target: 'http://www.2o3t.cn', // target host
  changeOrigin: true, // needed for virtual hosted sites
  ws: true, // proxy websockets
  pathRewrite: {
    '^/api/old-path': '/api/new-path', // rewrite path
    '^/api/remove/path': '/path' // remove base path
  },
  router: {
    // when request.headers.host == 'dev.localhost:3000',
    // override target 'http://www.2o3t.cn' to 'http://localhost:8000'
    'dev.localhost:3000': 'http://localhost:8000'
  }
};

// create the proxy (without context)
const exampleProxy = proxy(options);

app.use(exampleProxy)

app.use(ctx => {
    console.log(ctx.status);
});

app.listen(3003);

Context matching

Providing an alternative way to decide which requests should be proxied; In case you are not able to use the server's path parameter to mount the proxy or when you need more flexibility.

RFC 3986 path is used for context matching.

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment
  • path matching

  • proxy({...}) - matches any path, all requests will be proxied.

  • proxy('/', {...}) - matches any path, all requests will be proxied.

  • proxy('/api', {...}) - matches paths starting with /api

  • multiple path matching

  • proxy(['/api', '/ajax', '/someotherpath'], {...})

  • wildcard path matching

    For fine-grained control you can use wildcard matching. Glob pattern matching is done by micromatch. Visit micromatch or glob for more globbing examples.

  • proxy('**', {...}) matches any path, all requests will be proxied.

  • proxy('**/*.html', {...}) matches any path which ends with .html

  • proxy('/*.html', {...}) matches paths directly under path-absolute

  • proxy('/api/**/*.html', {...}) matches requests ending with .html in the path of /api

  • proxy(['/api/**', '/ajax/**'], {...}) combine multiple patterns

  • proxy(['/api/**', '!**/bad.json'], {...}) exclusion

    Note: In multiple path matching, you cannot use string paths and wildcard paths together.

  • custom matching

    For full control you can provide a custom function to determine which requests should be proxied or not.

  /**
   * @return {Boolean}
   */
  const filter = function(pathname, req) {
    return pathname.match('^/api') && req.method === 'GET';
  };

  const apiProxy = proxy(filter, { target: 'http://www.2o3t.cn' });

Options

http-proxy-middleware configuration options

new options

  • option.proxyBody: [Boolean|Function] Collect the results returned by the agent and assign them to ctx.body. Default: false.
option.proxyBody: true,
// or
option.proxyBody: function(json, proxyRes, req, res, ctx) {
    ctx.body = json;
}

License

The MIT License (MIT)

Copyright (c) 2018-2019 Zyao89

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文