Skip to content

Commit

Permalink
fix: Content-Length header automatically filled if it's not exists
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
muratcorlu committed Dec 12, 2019
1 parent 8a96a5c commit 3bb59f5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,3 @@ Every contribution is very welcome. Keep these in your mind when you want to mak
2. Keep code coverage 100% with your updated tests.
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.
4. Don't forget to update documentation(this readme file) about your changes.

## Troubleshooting

### I'm making a POST request with JSON by using bodyParser as middleware but `req.body` is always `{}`

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.
4 changes: 4 additions & 0 deletions src/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ class Request extends ReadableStream {
this.path = event.path;
this.params = event.pathParameters;

if (!this.get('Content-Length') && 'body' in event && event.body !== null) {
this.headers['content-length'] = event.body.length;
}

this.protocol = this.get('X-Forwarded-Proto')
this.secure = this.protocol === 'https';
this.ips = (this.get('X-Forwarded-For') || '').split(', ');
Expand Down
10 changes: 10 additions & 0 deletions src/request.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ describe('Request object', () => {

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

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

});

it('should handle content-length header if its not provided', () => {
delete event.headers['content-length'];
delete event.multiValueHeaders['content-length'];

const request = new Request(event);
const body = JSON.stringify(requestObject);
expect(request.get('content-length')).toBe(body.length);
})
});

0 comments on commit 3bb59f5

Please sign in to comment.