How do I parse a request body with content type: multipart/mixed in express?
A simple example of such request is below:
curl -H "Content-Type: multipart/mixed" -F "[email protected];type=application/json" -F "[email protected]" -X POST https://mysimpleapi.com
Body.json file is a simple json
[{
"name": "Test",
"age": "23"
},
{
"name": "Best",
"age": "24"
}]
and test.xml is just a regular file.
The curl request above looks like this:
{
"method": "POST",
"path": "/",
"query": {},
"headers": {
"x-forwarded-for": "163.47.149.248",
"x-forwarded-proto": "https",
"x-forwarded-port": "443",
"host": "mysimpleapi.com",
"x-amzn-trace-id": "Root=1-618e4f8e-2cc109560ddfb65a7b5822ef",
"content-length": "428",
"user-agent": "curl/7.68.0",
"accept": "*/*",
"content-type": "multipart/mixed; boundary=------------------------e2d73e2082b30c29"
},
"bodyRaw": "--------------------------e2d73e2082b30c29\r\nContent-Disposition: attachment; name=\"request\"; filename=\"body.json\"\r\nContent-Type: application/json\r\n\r\n[{\n \"name\": \"Test\",\n \"age\": \"23\"\n},\n{\n \"name\": \"Best\", \n \"age\": \"24\"\n}]\n\r\n--------------------------e2d73e2082b30c29\r\nContent-Disposition: attachment; name=\"file1\"; filename=\"test.xml\"\r\nContent-Type: application/xml\r\n\r\n\r\n--------------------------e2d73e2082b30c29--\r\n",
"body": "--------------------------e2d73e2082b30c29\r\nContent-Disposition: attachment; name=\"request\"; filename=\"body.json\"\r\nContent-Type: application/json\r\n\r\n[{\n \"name\": \"Test\",\n \"age\": \"23\"\n},\n{\n \"name\": \"Best\", \n \"age\": \"24\"\n}]\n\r\n--------------------------e2d73e2082b30c29\r\nContent-Disposition: attachment; name=\"file1\"; filename=\"test.xml\"\r\nContent-Type: application/xml\r\n\r\n\r\n--------------------------e2d73e2082b30c29--\r\n"
}
I want to get hold of the json object that's in the body of this request.
I was not able to find any documentation on how to parse this type of request. I know how to parse JSON and urlencoded form data from the request, but how do I parse a request like this on express? Is there any package that can do this parsing for me so that the request.body is not an empty object? Or I have to write some kind of parser myself(how do I do this?)?
CodePudding user response:
Answer this myself, dicer for node js can be used to do exactly this. The getting started example on dicer's npm worked just fine for the above example. https://www.npmjs.com/package/dicer