vagusx / koa-proxies Goto Github PK
View Code? Open in Web Editor NEWa [email protected]+ proxy middleware
Home Page: https://vagusx.github.io/koa-proxies/
License: MIT License
a [email protected]+ proxy middleware
Home Page: https://vagusx.github.io/koa-proxies/
License: MIT License
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.
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": {
Hi, #35 Had been merged on Jan 23 when did you release this new version?
To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:
.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.
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 🤖
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
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.
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.
The new version differs by 1 commits.
1aed97e
fix(package): update execa to version 1.0.0
See the full diff
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
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);
}
}
}
};
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.
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
.
The pr is merged, please publish the new version. thanks
After defining a proxy target that includes a URL prefix (http://myproxy/some/path), the requests are proxied to the correct target URL, but the path component of the proxy target is left out of the log message.
I.e. a call to http://myapp/endpoint would call http://myproxy/some/path/endpoint but log a redirect to http://myproxy/endpoint instead.
as title said, koa-proxies does not carry cookies, anyone helps?
Hi,
Does this support HTTPS? Do you have an example somewhere?
Thanks.
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 ?
It would be great to provide own logger or use current one as default option.
May I know why you deleted three properties from the opts
at Lin52?
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.
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 📦🚀
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
?
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.
Line 109 in 0d9619b
Can you advise how I can resolve this?
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:
However, when I access /proxy
, I cannot get the proxy results from end.
I know that the return result is handled through
proxyRes
, but what causes this difference?
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 ?
output:
I need to set different target depending on some header in request.
Example:
ctx.headers['foo'] === 'bar' ==> target: 'http://localhost:3000/'
ctx.headers['foo'] === 'baz' ==> target: 'http://localhost:3001/'
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.
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.
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
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Firstly, thanks for this library, it's got a great api and works well when it's used as a single proxy middleware.
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) {
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.