From 09d05d5856159e14924bf3a6e4b941beb22678a4 Mon Sep 17 00:00:00 2001 From: Howie Zhao Date: Sun, 7 Jul 2024 21:05:52 +0800 Subject: [PATCH] fix(fix-request-body): support '+json' content-type suffix (#1015) * fix(fix-request-body): add fix for '+json' ending * test: add unit test * fix: fix ut error * docs: Update CHANGELOG.md --------- Co-authored-by: Steven Chim <655241+chimurai@users.noreply.github.com> --- CHANGELOG.md | 1 + src/handlers/fix-request-body.ts | 2 +- test/unit/fix-request-body.spec.ts | 14 ++++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8588f339..f9a29824 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - ci(package): npm package provenance - fix(logger-plugin): log target port when router option is used - refactor: fix circular dependencies +- fix(fix-request-body): support '+json' content-type suffix ## [v3.0.0](https://github.com/chimurai/http-proxy-middleware/releases/tag/v3.0.0) diff --git a/src/handlers/fix-request-body.ts b/src/handlers/fix-request-body.ts index c8c2aa1e..4fe1e458 100644 --- a/src/handlers/fix-request-body.ts +++ b/src/handlers/fix-request-body.ts @@ -23,7 +23,7 @@ export function fixRequestBody( proxyReq.write(bodyData); }; - if (contentType && contentType.includes('application/json')) { + if (contentType && (contentType.includes('application/json') || contentType.includes('+json'))) { writeBody(JSON.stringify(requestBody)); } diff --git a/test/unit/fix-request-body.spec.ts b/test/unit/fix-request-body.spec.ts index fe254318..b176506e 100644 --- a/test/unit/fix-request-body.spec.ts +++ b/test/unit/fix-request-body.spec.ts @@ -57,6 +57,20 @@ describe('fixRequestBody', () => { expect(proxyRequest.write).toHaveBeenCalledWith(expectedBody); }); + it('should write when body is not empty and Content-Type ends with +json', () => { + const proxyRequest = fakeProxyRequest(); + proxyRequest.setHeader('content-type', 'application/merge-patch+json; charset=utf-8'); + + jest.spyOn(proxyRequest, 'setHeader'); + jest.spyOn(proxyRequest, 'write'); + + fixRequestBody(proxyRequest, createRequestWithBody({ someField: 'some value' })); + + const expectedBody = JSON.stringify({ someField: 'some value' }); + expect(proxyRequest.setHeader).toHaveBeenCalledWith('Content-Length', expectedBody.length); + expect(proxyRequest.write).toHaveBeenCalledWith(expectedBody); + }); + it('should write when body is not empty and Content-Type is application/x-www-form-urlencoded', () => { const proxyRequest = fakeProxyRequest(); proxyRequest.setHeader('content-type', 'application/x-www-form-urlencoded');