Code Monkey home page Code Monkey logo

koa-proxies's Introduction

Koa Proxies

NPM

Node.js CI Coverage NPM Downloads Greenkeeper badge

[email protected]/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
}))

The 2nd parameter options can be a function. It will be called with the path matching result (see path-match for details) and Koa ctx object. You can leverage this feature to dynamically set proxy. Here is an example:

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

const app = new Koa()

// middleware
app.use(proxy('/octocat/:name', (params, ctx) => {
  return {
    target: 'https://api.github.com/',
    changeOrigin: true,
    rewrite: () => `/users/${params.name}`,
    logs: true
  }})
)

Moreover, if the options function return false, then the proxy will be bypassed. This allows the middleware to bail out even if path matching succeeds, which could be helpful if you need complex logic to determine whether to proxy or not.

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

koa-proxies's People

Contributors

benukel avatar chase2v avatar cytle avatar dkurilo avatar greenkeeper[bot] avatar janchvala avatar ljbc1994 avatar oroce avatar pikadun avatar raphaelsoul avatar snyk-bot avatar vagusx avatar whenlit avatar xc1427 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

koa-proxies's Issues

PATCH method doesn't proxy request body

It seems like proxying methods like PATCH having some payload in the body doesn't arrive at server.
Did I do something wrong or is it a bug?

Works totally fine for GET requests but PATCH fails.

const proxyTable = {
    'proxy/api/': {
        target: `${targeturl}`,
        rewrite: path => path.replace(/\/proxy/, ''),
        logs: true,
        changeOrigin: true,
        headers: {
            Authorization: `Bearer ${token}`
        },
        secure: true,
        events: {
            error(err, req, res) {
                log.error(err);
            }
        }
    }
};

should middleware obtain the results of proxy?

const Koa = require("koa");
const http = require("http");
const proxy = require("koa-proxies");
const router = require("koa-router")();

const app = new Koa();

app.use(async (ctx, next) => {
  console.log("start");
  await next();
  console.log("end", ctx.body);
});

app.use(
  proxy("/proxy", (params, ctx) => {
    ctx.respond = false;

    return {
      target: "http://127.0.0.1:22311",
      changeOrigin: true,
    };
  })
);

router.get("/test", async function (ctx, next) {
  ctx.body = "test";
  next();
});

app.use(router.routes(), router.allowedMethods());

var server = http.createServer(app.callback());

const hostname = "0.0.0.0";
const port = 8081;

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

When I access /test, I can get the following results:
image

However, when I access /proxy, I cannot get the proxy results from end.
image

I know that the return result is handled throughproxyRes, but what causes this difference?

Doesn't support event listening for multiple proxies

Firstly, thanks for this library, it's got a great api and works well when it's used as a single proxy middleware.

Problem

When registering multiple proxy middleware, the event listeners are only set up for the first proxy but not the subsequent proxies. This should either be supported or there should be a disclaimer on the README to detail that it's not supported. It's more of a bug because the proxy works fine it's just the events that don't get triggered.

The problem is essentially here:

// llne 20
let eventRegistered = false

// line 58
if (events && typeof events === 'object' && !eventRegistered) {

Recreate

function logFirstRequest() {
   console.log('gets called')
}

function logSecondRequest() {
   console.log('doesnt get called')
}

// First middleware
app.use(proxy('/first-test', {
        target: 'http://localhost:5000',
        events: {
            proxyRes: logFirstRequest,
        },
    })
)

// Second middleware
app.use(proxy('second-test', {
        target: 'http://localhost:4999',
        events: {
            proxyRes: logSecondRequest,
        },
    })
)

I've got a fix but will require quite a big change in functionality, if this is something that you'd like fixed?

koa-proxies should be In front of the koa-bodyparser.

I test koa proxies in my project, I find a weird bug when it works with koa-bodyparser.

// this works well.
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,
  rewrite: path => path
}))
app.use(bodyParser())
app.listen(8080);
// this works with bug "socket hang up".
const Koa = require('koa');
const app = new Koa();
const proxy = require('koa-proxies')
const bodyParser = require('koa-bodyparser');
app.use(bodyParser())

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

app.listen(8080);

the only difference is the sequence of the bodyParser and proxy.
I guess the post data will be consumed by the bodyParser, that is not what we want and will not proxy to our target, so it should be placed behind the proxy.

It will save our time if document it. Thank you.

readme.md

const Koa = require('koa')
const proxy = require('koa-proxies')
const httpsProxyAgent = require('koa-proxies')

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'),
  rewrite: path => path.replace(/^\/octocat(\/|\/\w+)?$/, '/vagusx'),
  logs: true
}))

can httpsProxyAgent be newed ?
it is the same as require('koa-proxies'), which is an arrow function ?

Customize logger

It would be great to provide own logger or use current one as default option.

HTTPS example?

Hi,
Does this support HTTPS? Do you have an example somewhere?
Thanks.

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

ctx refrence error

const querystring = require('querystring')
const proxy = require('koa-proxies')

module.exports = (app) => {
  ......
  app.router.all(
    `${config.prefix}/(.*)`,
    proxy(`${config.prefix}/(.*)`, (params, ctx) => {

     console.log('return options function call : ' + ctx.url)

      return {
        logs: true,
        changeOrigin: true,
        target: config.uasSvc,
        events: {
          proxyReq(proxyReq, req, res) {


            console.log('proxy req event call: ' + ctx.url)
            
          },
        },
      }
    })
  )
}

I fetch twice with different url, why the secondary proxyReq function output is the FIRST fetch's url ?
CleanShot 2023-07-20 at 16 18 16@2x

output:

CleanShot 2023-07-20 at 16 19 02@2x

An in-range update of chai-http is breaking the build 🚨

Version 4.1.0 of chai-http was just published.

Branch Build failing 🚨
Dependency chai-http
Current Version 4.0.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

chai-http is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests passed on CircleCI! (Details).
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes 4.1.0 / 2018-08-03

This is a minor update to fix a bug with keepOpen() now allowing close() to be called, and also some additional support for other http libraries - namely the http-errors library.

Community Contributions

Code Features & Fixes

  • #219 Allow for status / statusCode to exist on the prototype (by @austince)
  • #217 Enable closing after keepOpen() has been called (by @martypdx)
Commits

The new version differs by 6 commits.

  • 2c342c8 Merge pull request #220 from austince/release/4.1.0
  • 6efbd83 4.1.0
  • d515691 Merge pull request #219 from austince/fix/inherited-properties
  • 5de4b03 fix: Allow checking properties of prototype and update tests
  • 1af976d Merge pull request #217 from martypdx/master
  • 25600aa fix: test and change for closing "keepOpen()" server, fixes #189

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

IBaseKoaProxiesOptions Should Extend http-proxy Server.ServerOptions

Shouldn't this line include extends Server.ServerOptions from the http-proxy package?
https://github.com/vagusX/koa-proxies/blob/master/index.d.ts#L7

Considering the fact that it looks like the options object is being passed along wholesale to http-proxy, seems like it would make sense: https://github.com/vagusX/koa-proxies/blob/master/index.js#L65-L70 and https://github.com/vagusX/koa-proxies/blob/master/index.js#L109

I was trying to add the buffer option (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/http-proxy/index.d.ts#L187), but TS is choking on the missing property on IBaseKoaProxiesOptions.

An in-range update of semantic-release is breaking the build 🚨

Version 15.9.11 of semantic-release was just published.

Branch Build failing 🚨
Dependency semantic-release
Current Version 15.9.10
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

semantic-release is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: Your tests passed on CircleCI! (Details).
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes v15.9.11

15.9.11 (2018-08-26)

Bug Fixes

  • package: update execa to version 1.0.0 (1aed97e)
Commits

The new version differs by 1 commits.

  • 1aed97e fix(package): update execa to version 1.0.0

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error callback blocks all custom error handlers

Hi, thanks a lot for this library. It makes my life easier.

One thing though: when anything goes wrong in proxying, let's say because the domain cannot be found, any error messages are eaten by the callback starting in line 109:

proxy.web(ctx.req, ctx.res, httpProxyOpts, e => {
  const status = {
    ECONNREFUSED: 503,
    ETIMEOUT: 504
  }[e.code]
  ctx.status = status || 500
  resolve()
})

Because the http-proxy package does not emit the error event when a callback is specified, there is no way to get to those error messages in your package.

Here is the relevant bit from http-proxy/lib/http-proxy/passes/web-incoming.js (clb === callback):

if (clb) {
  clb(err, req, res, url);
} else {
  server.emit('error', err, req, res, url);
}

So, it would be nice if koa-proxies would call the error handler manually if it is specified. I hope you agree. I'll add a PR shortly.

ERR_TLS_CERT_ALTNAME_INVALID from proxy.web()

I'm trying to use koa-proxies to proxy requests through to Amazon AWS, but the proxied file is returning with status 500.

Investigating, I can see that the call to proxy.web() is returning an error [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames: Host: www.mtl.local. is not in the cert's altnames: DNS:*.s3.amazonaws.com, DNS:s3.amazonaws.com.

proxy.web(ctx.req, ctx.res, httpProxyOpts, e => {

Can you advise how I can resolve this?

The Promise returned by this middleware never get resolved

It bothered me a lot that I found that the callback of proxy.web in http-proxy is invoked only when errors occurred. The method is not a sync function and has no callbacks that are guaranteed to be triggered. That's an insane feature (or bug), which made me sought and tried a lot of ways to solve it. But it was in vain.
Then I saw your code returning a Promise without taking any measure to deal with that "feature". I was wondering if I was wrong? It was just so simple? So I tested your code once and once again. Finally, I drew a conclusion that the Promise didn't get resolved at all.

Typings support requested

Thanks for creating and sharing this great library: it makes it very easy to proxy requests to other sites.

As I'm using TypeScript, I was wondering if you would consider adding a typings file to the project too, making it easier to import your library using import proxies from 'koa-proxies';? Currently, I need to add the following code snippet to my project in file koa-proxies.d.ts:

declare module "koa-proxies" {
  export interface IKoaProxies {
    target: string;
    changeOrigin?: boolean;
    logs?: boolean;
    agent?: any;
    rewrite?: (path: string) => string;
  }

  export default function proxy(path: string, options: IKoaProxies): Promise;
}

In order to support it directly out-of-the-box, all you need to do is add an index.d.ts, e.g.

export interface IKoaProxies {
  target: string;
  changeOrigin?: boolean;
  logs?: boolean;
  agent?: any;
  rewrite?: (path: string) => string;
}

export default function proxy(path: string, options: IKoaProxies): Promise;

and add a reference to it in the package.json, i.e. this

  "main": "index.js",
  "scripts": { 

becomes

  "main": "index.js",
  "typings": "index.d.ts",
  "scripts": {

Inspect proxied response body?

I'm writing a proxy service that needs to inspect the body being proxied back to the client. Is it possible to add this on the ctx.response.body?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.