Skip to content

Commit 3bb59f5

Browse files
committed
fix: Content-Length header automatically filled if it's not exists
AWS API Gateway doesn't pass content-length header to lambda function. As a result of this body-parser can not parse body. This fix calculates Content-Length with the size of body if there is no content-length header and if there is a body.
1 parent 8a96a5c commit 3bb59f5

File tree

3 files changed

+14
-6
lines changed

3 files changed

+14
-6
lines changed

README.md

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,3 @@ Every contribution is very welcome. Keep these in your mind when you want to mak
128128
2. Keep code coverage 100% with your updated tests.
129129
3. Check your changes with a Lambda environment. You can use [SAM-CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) to test on your local.
130130
4. Don't forget to update documentation(this readme file) about your changes.
131-
132-
## Troubleshooting
133-
134-
### I'm making a POST request with JSON by using bodyParser as middleware but `req.body` is always `{}`
135-
136-
Please check your `Content-Type` and `Content-Length` request headers. For JSON requests `Content-Type` should be `application/json` and `Content-Length` should be size(in bytes) of JSON string in body.

src/request.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ class Request extends ReadableStream {
3030
this.path = event.path;
3131
this.params = event.pathParameters;
3232

33+
if (!this.get('Content-Length') && 'body' in event && event.body !== null) {
34+
this.headers['content-length'] = event.body.length;
35+
}
36+
3337
this.protocol = this.get('X-Forwarded-Proto')
3438
this.secure = this.protocol === 'https';
3539
this.ips = (this.get('X-Forwarded-For') || '').split(', ');

src/request.spec.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ describe('Request object', () => {
6969

7070
it('should read headers as empty object if there is no headers', () => {
7171
delete event.multiValueHeaders;
72+
delete event.body;
7273
const request = new Request(event);
7374

7475
expect(request.headers).toEqual({});
@@ -136,4 +137,13 @@ describe('Request object', () => {
136137
expect(request.acceptsLanguages('tr', 'en')).toBe('tr');
137138

138139
});
140+
141+
it('should handle content-length header if its not provided', () => {
142+
delete event.headers['content-length'];
143+
delete event.multiValueHeaders['content-length'];
144+
145+
const request = new Request(event);
146+
const body = JSON.stringify(requestObject);
147+
expect(request.get('content-length')).toBe(body.length);
148+
})
139149
});

0 commit comments

Comments
 (0)