koa-proxiesa koa@2.x proxy middleware

联合创作 · 2023-09-21 13:27

Koa Proxies


NPM


Coverage NPM Downloads Greenkeeper badge



Koa@2.x/next middlware for http proxy



Powered by http-proxy.


Installation



$ npm install koa-proxies --save


Options


http-proxy events



options.events = {
error (err, req, res) { },
proxyReq (proxyReq, req, res) { },
proxyRes (proxyRes, req, res) { }
}


log option



// enable log
options.logs = true; // or false

// custom log function
options.logs = (ctx, target) {
console.log('%s - %s %s proxy to -> %s', new Date().toISOString(), ctx.req.method, ctx.req.oldPath, new URL(ctx.req.url, target))
}


Usage



// dependencies
const Koa = require('koa')
const proxy = require('koa-proxies')
const httpsProxyAgent = require('https-proxy-agent')

const app = new Koa()

// middleware
app.use(proxy('/octocat', {
target: 'https://api.github.com/users',
changeOrigin: true,
agent: new httpsProxyAgent('http://1.2.3.4:88'), // if you need or just delete this line
rewrite: path => path.replace(/^\/octocat(\/|\/\w+)?$/, '/vagusx'),
logs: true
}))


Attention


Please make sure that koa-proxies is in front of koa-bodyparser to avoid this issue 55



const Koa = require('koa')
const app = new Koa()
const proxy = require('koa-proxies')
const bodyParser = require('koa-bodyparser')

app.use(proxy('/user', {
target: 'http://example.com',
changeOrigin: true
}))

app.use(bodyParser())


JavaScript Style Guide

浏览 17
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报