2

On my AWS lambda function i have access to an event json which holds a parameter called: body. the issue is this is a raw body string (not parsed into individual parameters).

{
  input: {
    body: "------WebKitFormBoundarys3wLu6HlaCBrIExe\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n------WebKitFormBoundarys3wLu6HlaCBrIExe\r\nContent-Disposition: form-data; name=\"media[]\"\r\n\r\nhthtth\r\n------WebKitFormBoundarys3wLu6HlaCBrIExe\r\nContent-Disposition: form-data; name=\"media[]\"\r\n\r\nlololol\r\n------WebKitFormBoundarys3wLu6HlaCBrIExe--\r\n"
  }
}

I'd like to take that and turn into:

{
  foo: 'bar',
  media: [
    "grgkoerpkge",
    "twepgbopcib"
  ]
}

I'd prefer not to use some bloated express server just to parse a body string.

P.S. I've tried to use body-parser but it seems like it only works with express as a middleware

CodeOverload
  • 47,274
  • 54
  • 131
  • 219
  • You can find the solution [here](https://stackoverflow.com/questions/38599028/parse-multipart-form-data-from-body-as-string-on-aws-lambda) – sayan saha Nov 01 '20 at 00:43

4 Answers4

1
const {URLSearchParams} = require('url')
const sp = new URLSearchParams(event.body)
Oded Breiner
  • 28,523
  • 10
  • 105
  • 71
0

Encountered similar issue recently, as content-type in request was plain text format, I used querystring, built in module in node js to parse body string, more about querystring

const querystring = require('querystring');

& in lambda handler,

var jsonData = querystring.parse(event.body);
dc7
  • 401
  • 1
  • 4
  • 13
  • This only works when the body `Content-Type` is `application/x-www-form-urlencoded`, doesn't work for `multipart/form-data`. – sayan saha Oct 31 '20 at 23:30
-1

Send it to your lambda as JSON.

Then, in your lambda (if you use lambda-proxy integration), parse it by using JSON.parse(event.body).

Noel Llevares
  • 15,018
  • 3
  • 57
  • 81
-1

You'r passing the params by form or with the "Content-Type" in the header "application/x-www-form-urlencoded".

You shoukd pass it with "application/json"

Guerra
  • 2,792
  • 1
  • 22
  • 32