Skip to content

Bin-Huang/koa-proxying

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

koa-proxying

Just a very simple HTTP proxying tool for koa, wrapping http-proxy but easier to use in koa.

const proxy = require('koa-proxying')
const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
  const path = ctx.request.path

  if (path.startsWith('/common-user')) {
    await proxy(ctx, { target: 'https://user-service:8080' })
    return
  }

  if (ctx.state.user.isAdmin) {
    await proxy(ctx, { target: 'https://admin-service:8080' })
    return
  }

  ctx.body = 'forbiden'
})

Install

npm install koa-proxying --save

How to use

await proxy(ctx, option)

await proxy(ctx, { target: 'target service url' })

The option will be passed to http-proxy, see more details

Some advanced cases

Set response headers previous:

ctx.set('by-proxy', 'true')
await proxy(ctx, { target: 'https://target-service' })

Modify headers and query (request to target service):

ctx.query = { pkg_name: 'koa-proxying' }
ctx.request.header = { 'x-real-ip': ctx.ip, ...ctx.request.header }
await proxy(ctx, { target: 'https://target-service' })

Set proxy request path:

if (ctx.path === '/user/account-center') {
  ctx.path = '/account'
  await proxy(ctx, { target: 'https://target-service', prependPath: false })
}
// https://proxy-service/user/account-center
// --> 
// https://target-service/account

Load balance:

await proxy(ctx, { target: getUrlFromLoadBalancer() })

NOTE

If target service is a koa application, it is recommended to set app.proxy = true on target service.

If you wants more features about proxying, it is http-proxy. By the way, this package koa-proxying is just a simple wrapping version of http-proxy, but easier to use in some cases.

About

Just a very simple HTTP proxying tool for koa

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published