开发者社区> 镜像站> NPM> koa2-simple-proxy
koa2-simple-proxy
simple http-proxy for koa2
Last updated 3 years ago by fengxinming .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install koa2-simple-proxy 
SYNC missed versions from official npm registry.

koa2-simple-proxy

Note: that koa2-simple-proxy supports for koa2


Usage

Note: if you use [/api and /api2] as prefixes, the /api2 should be in front of the /api


const Koa = require('koa');
const proxy = require('koa2-simple-proxy');
const app = new Koa();

// x-response-time
app.use(async(ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger
app.use(async(ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// proxy
app.use(proxy('/rest', 'http://192.168.1.240/api2'));
app.use(proxy(['/api2', '/api'], 'http://192.168.1.240/api2'));
app.use(proxy('/api3', 'http://192.168.1.240/api2', {
  events: {
    error(err, req, res) {
      res.writeHead(500, err.message, {
        'Content-Type': 'application/json'
      });
      res.end(JSON.stringify(Object.assign({}, err, {
        message: err.message, // 有时候message字段不能被输出
        url: req.url
      })));
    }
  }
}));

// response
app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(9527, () => {
  console.log(`Listening on 9527`);
});

Current Tags

  • 1.0.0                                ...           latest (3 years ago)

1 Versions

  • 1.0.0                                ...           3 years ago
Maintainers (1)
Downloads
Today 0
This Week 1
This Month 1
Last Day 1
Last Week 3
Last Month 13
Dependencies (1)
Dev Dependencies (1)