Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use base node http types #723

Closed
wants to merge 13 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
293 changes: 138 additions & 155 deletions README.md

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion examples/browser-sync/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-
/**
* Configure proxy middleware
*/
const jsonPlaceholderProxy = createProxyMiddleware('/users', {
const jsonPlaceholderProxy = createProxyMiddleware({
target: 'http://jsonplaceholder.typicode.com',
pathFilter: '/users',
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
logLevel: 'debug',
});
Expand Down
2 changes: 1 addition & 1 deletion examples/websocket/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<body>
<h2>WebSocket demo</h2>

<p>Proxy <code>ws://localhost:3000</code> to <code>ws://echo.websocket.org</code></p>
<p>Proxy <code>ws://localhost:3000</code> to <code>ws://ws.ifelse.io</code></p>

<fieldset id="configuration">
<p>
Expand Down
4 changes: 2 additions & 2 deletions examples/websocket/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ const { createProxyMiddleware } = require('../../dist'); // require('http-proxy-
/**
* Configure proxy middleware
*/
const wsProxy = createProxyMiddleware('/', {
target: 'http://echo.websocket.org',
const wsProxy = createProxyMiddleware({
target: 'http://ws.ifelse.io',
// pathRewrite: {
// '^/websocket' : '/socket', // rewrite path.
// '^/removepath' : '' // remove path.
Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ module.exports = {
testEnvironment: 'node',
coverageReporters: ['text', 'lcov'],
collectCoverageFrom: ['src/**/*.*'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};
2 changes: 2 additions & 0 deletions jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
console.log = jest.fn();
console.info = jest.fn();
chimurai marked this conversation as resolved.
Show resolved Hide resolved
8 changes: 0 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,14 +90,6 @@
"is-plain-obj": "^3.0.0",
"micromatch": "^4.0.2"
},
"peerDependencies": {
"@types/express": "^4.17.13"
},
"peerDependenciesMeta": {
"@types/express": {
"optional": true
}
},
"engines": {
"node": ">=12.0.0"
},
Expand Down
10 changes: 4 additions & 6 deletions recipes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,13 @@ http-proxy-middleware uses Nodejitsu's [http-proxy](https://github.com/nodejitsu
const { createProxyMiddleware } = require('http-proxy-middleware');
const winston = require('winston');

/**
* Context matching: decide which path(s) should be proxied. (wildcards supported)
**/
const context = '/api';

/**
* Proxy options
*/
const options = {
// decide which path(s) should be proxied. (wildcards supported)
pathFilter: '/api',

// hostname to the target server
target: 'http://localhost:3000',

Expand Down Expand Up @@ -104,5 +102,5 @@ const options = {
/**
* Create the proxy middleware, so it can be used in a server.
*/
const apiProxy = createProxyMiddleware(context, options);
const apiProxy = createProxyMiddleware(options);
```
8 changes: 4 additions & 4 deletions recipes/basic.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ This example will create a basic proxy middleware.
```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware('/api', { target: 'http://localhost:3000' });
// \____/ \________________________________/
// | |
// context options
const apiProxy = createProxyMiddleware({
pathFilter: '/api',
target: 'http://localhost:3000',
});
```

## Alternative configuration
Expand Down
38 changes: 22 additions & 16 deletions recipes/context-matching.md → recipes/pathFilter.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Context matching
# Path Filter

Determine which requests should be proxied.

Context matching is optional and is useful in cases where you are not able to use the regular [middleware mounting](http://expressjs.com/en/4x/api.html#app.use).
`pathFilter` is optional and is useful in cases where you are not able to use the regular [middleware mounting](http://expressjs.com/en/4x/api.html#app.use).

The [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for context matching.
The [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for `pathFilter`.

```
```text
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
Expand All @@ -15,25 +15,22 @@ The [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used f

`http-proxy-middleware` offers several ways to do this:

<!-- MarkdownTOC autolink=true bracket=round -->

- [Path](#path)
- [Multi Path](#multi-path)
- [Wildcard](#wildcard)
- [Multi Wildcard](#multi-wildcard)
- [Wildcard / Exclusion](#wildcard--exclusion)
- [Custom filtering](#custom-filtering)

<!-- /MarkdownTOC -->

## Path

This will match paths starting with `/api`

```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware('/api', {
const apiProxy = createProxyMiddleware({
pathFilter: '/api',
target: 'http://localhost:3000',
});

Expand All @@ -47,7 +44,10 @@ This will match paths starting with `/api` or `/rest`
```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware(['/api', '/rest'], { target: 'http://localhost:3000' });
const apiProxy = createProxyMiddleware({
pathFilter: ['/api', '/rest'],
target: 'http://localhost:3000',
});

// `/api/foo/bar` -> `http://localhost:3000/api/foo/bar`
// `/rest/lorum/ipsum` -> `http://localhost:3000/rest/lorum/ipsum`
Expand All @@ -60,7 +60,8 @@ This will match paths starting with `/api/` and should also end with `.json`
```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware('/api/**/*.json', {
const apiProxy = createProxyMiddleware({
pathFilter: '/api/**/*.json',
target: 'http://localhost:3000',
});
```
Expand All @@ -72,26 +73,28 @@ Multiple wildcards can be used.
```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware(['/api/**/*.json', '/rest/**'], {
const apiProxy = createProxyMiddleware({
pathFilter: ['/api/**/*.json', '/rest/**'],
target: 'http://localhost:3000',
});
```

## Wildcard / Exclusion

This example will create a proxy with wildcard context matching.
This example will create a proxy with globs.

```javascript
const { createProxyMiddleware } = require('http-proxy-middleware');

const apiProxy = createProxyMiddleware(['foo/*.js', '!bar.js'], {
const apiProxy = createProxyMiddleware({
pathFilter: ['foo/*.js', '!bar.js'],
target: 'http://localhost:3000',
});
```

## Custom filtering

Write your custom context matching function to have full control on the matching behavior.
Write your custom `pathFilter` function to have full control on the matching behavior.
The request `pathname` and `req` object are provided to determine which requests should be proxied or not.

```javascript
Expand All @@ -101,5 +104,8 @@ const filter = function (pathname, req) {
return pathname.match('^/api') && req.method === 'GET';
};

const apiProxy = createProxyMiddleware(filter, { target: 'http://localhost:3000' });
const apiProxy = createProxyMiddleware({
pathFilter: filter,
target: 'http://localhost:3000',
});
```
62 changes: 0 additions & 62 deletions recipes/shorthand.md

This file was deleted.

8 changes: 4 additions & 4 deletions src/_handlers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type * as express from 'express';
import type { Options } from './types';
import type { Request, Response, Options } from './types';
import type * as httpProxy from 'http-proxy';
import { getInstance } from './logger';
import { getUrl } from './url';
Copy link
Author

@cdaringe cdaringe Mar 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👀 as mentioned in issue discussions, we now have clarity that we cannot just use req.url--it's mutated from express. thus, from the Request type, I have now dropped url: string, as it's unsafe to access in the codebase. getUrl is a safe, express & IncomingMessage compatible accessor

const logger = getInstance();

export function init(proxy: httpProxy, option: Options): void {
Expand Down Expand Up @@ -53,7 +53,7 @@ export function getHandlers(options: Options) {
return handlers;
}

function defaultErrorHandler(err, req: express.Request, res: express.Response) {
function defaultErrorHandler(err, req: Request, res: Response) {
// Re-throw error. Not recoverable since req & res are empty.
if (!req && !res) {
throw err; // "Error: Must provide a proper URL as target"
Expand All @@ -79,7 +79,7 @@ function defaultErrorHandler(err, req: express.Request, res: express.Response) {
}
}

res.end(`Error occurred while trying to proxy: ${host}${req.url}`);
res.end(`Error occurred while trying to proxy: ${host}${getUrl(req)}`);
}

function logClose(req, socket, head) {
Expand Down
90 changes: 0 additions & 90 deletions src/config-factory.ts

This file was deleted.

Loading