Skip to content
This repository has been archived by the owner on Mar 29, 2022. It is now read-only.

Commit

Permalink
Fix proxied binary bodies wrongly converted to utf-8
Browse files Browse the repository at this point in the history
Closes #3
  • Loading branch information
Guillaume committed Apr 12, 2021
1 parent 5e176a3 commit ac1a5bc
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 15 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@mockoon/commons-server",
"description": "Mockoon's commons server library. Used in Mockoon desktop application and CLI.",
"version": "1.0.2",
"version": "1.0.3",
"author": {
"name": "Guillaume Monnet",
"email": "hi@255kb.dev",
Expand Down
23 changes: 11 additions & 12 deletions src/libs/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,22 +189,26 @@ export class MockoonServer extends (EventEmitter as new () => TypedEmitter<
'Content-Type'
);

request.setEncoding('utf8');
request.body = '';
const rawBody: Buffer[] = [];

request.on('data', (chunk) => {
request.body += chunk;
rawBody.push(Buffer.from(chunk, 'binary'));
});

request.on('end', () => {
request.rawBody = Buffer.concat(rawBody);
request.body = request.rawBody.toString('utf8');

try {
if (requestContentType) {
if (requestContentType.includes('application/json')) {
request.bodyJSON = JSON.parse(request.body);
} else if (
requestContentType.includes('application/x-www-form-urlencoded')
) {
request.bodyForm = qsParse(request.body, { depth: 10 });
request.bodyForm = qsParse(request.body, {
depth: 10
});
}
}
} catch (error) {
Expand Down Expand Up @@ -479,14 +483,9 @@ export class MockoonServer extends (EventEmitter as new () => TypedEmitter<
request
);

if (request.body) {
proxyReq.setHeader(
'Content-Length',
Buffer.byteLength(request.body)
);

// re-stream the body (intercepted by body parser method) and mark as proxied
proxyReq.write(request.body);
// re-stream the body (intercepted by body parser method)
if (request.rawBody) {
proxyReq.write(request.rawBody);
}
},
onProxyRes: (
Expand Down
1 change: 1 addition & 0 deletions src/typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
declare namespace Express {
export interface Request {
proxied: boolean;
rawBody: Buffer;
bodyForm: any;
bodyJSON: any;
}
Expand Down

0 comments on commit ac1a5bc

Please sign in to comment.