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

feat: try to proxy body even after body-parser middleware #492

Merged
merged 9 commits into from
Apr 24, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"@types/ws": "^7.4.0",
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",
"body-parser": "^1.19.0",
"browser-sync": "^2.26.14",
"connect": "^3.7.0",
"eslint": "^7.23.0",
Expand Down
26 changes: 26 additions & 0 deletions src/handlers/fix-request-body.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ClientRequest } from 'http';
import type { Request } from '../types';
import * as querystring from 'querystring';

/**
* Fix proxied body if bodyParser is involved.
*/
export function fixRequestBody(proxyReq: ClientRequest, req: Request): void {
if (!req.body || !Object.keys(req.body).length) {
return;
}

const contentType = proxyReq.getHeader('Content-Type') as string;
const writeBody = (bodyData: string) => {
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
chimurai marked this conversation as resolved.
Show resolved Hide resolved
proxyReq.write(bodyData);
};

if (contentType.includes('application/json')) {
writeBody(JSON.stringify(req.body));
}

if (contentType === 'application/x-www-form-urlencoded') {
writeBody(querystring.stringify(req.body));
}
}
1 change: 1 addition & 0 deletions src/handlers/public.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { responseInterceptor } from './response-interceptor';
export { fixRequestBody } from './fix-request-body';
6 changes: 3 additions & 3 deletions test/e2e/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import * as express from 'express';
import { Express, RequestHandler } from 'express';

export { createProxyMiddleware, responseInterceptor } from '../../dist/index';
export { createProxyMiddleware, responseInterceptor, fixRequestBody } from '../../dist/index';

export function createApp(middleware: RequestHandler): Express {
export function createApp(...middleware: RequestHandler[]): Express {
chimurai marked this conversation as resolved.
Show resolved Hide resolved
const app = express();
app.use(middleware);
app.use(...middleware);
return app;
}

Expand Down
40 changes: 39 additions & 1 deletion test/e2e/http-proxy-middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { createProxyMiddleware, createApp, createAppWithPath } from './_utils';
import { createProxyMiddleware, createApp, createAppWithPath, fixRequestBody } from './_utils';
import * as request from 'supertest';
import { Mockttp, getLocal, CompletedRequest } from 'mockttp';
import { Request, Response } from '../../src/types';
import { NextFunction } from 'express';
import * as bodyParser from 'body-parser';

describe('E2E http-proxy-middleware', () => {
describe('http-proxy-middleware creation', () => {
Expand Down Expand Up @@ -78,6 +79,43 @@ describe('E2E http-proxy-middleware', () => {
});
});

describe('basic setup with configured body-parser', () => {
it('should proxy request body from form', async () => {
agent = request(
createApp(
bodyParser.urlencoded({ extended: false }),
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
onProxyReq: fixRequestBody,
})
)
);

await mockTargetServer.post('/api').thenCallback((req) => {
expect(req.body.text).toBe('foo=bar&bar=baz');
return { status: 200 };
});
await agent.post('/api').send('foo=bar').send('bar=baz').expect(200);
});
it('should proxy request body from json', async () => {
agent = request(
createApp(
bodyParser.json(),
createProxyMiddleware('/api', {
target: `http://localhost:${mockTargetServer.port}`,
onProxyReq: fixRequestBody,
})
)
);

await mockTargetServer.post('/api').thenCallback((req) => {
expect(req.body.json).toEqual({ foo: 'bar', bar: 'baz' });
return { status: 200 };
});
await agent.post('/api').send({ foo: 'bar', bar: 'baz' }).expect(200);
});
});

describe('custom context matcher/filter', () => {
it('should have response body: "HELLO WEB"', async () => {
const filter = (path, req) => {
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1483,7 +1483,7 @@ blob@0.0.5:
resolved "https://registry.yarnpkg.com/blob/-/blob-0.0.5.tgz#d680eeef25f8cd91ad533f5b01eed48e64caf683"
integrity sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig==

body-parser@1.19.0, body-parser@^1.15.2:
body-parser@1.19.0, body-parser@^1.15.2, body-parser@^1.19.0:
version "1.19.0"
resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.19.0.tgz#96b2709e57c9c4e09a6fd66a8fd979844f69f08a"
integrity sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==
Expand Down