i want to build an API as a serverless AWS Lambda Function and use ClaudiaJS as a framework. However, when passing a JSON object to the POST route, i cannot parse the contents of request.body correctly since they are of the type "string" instead of type "object". If this were an express node.js backend, i would just use bodyParser, but in this case i cannot. Any help appreciated :)
I tried JSON.parse(req.body), but to no avail.
This is the code for the POST route
var ApiBuilder = require('claudia-api-builder'),
api = new ApiBuilder();
module.exports = api;
api.post('/upload', (req, res) => {
return req.body; //I return the body for debugging purposes
});
When posting the JSON Object to the service using POSTMAN (content-type:application/json)
{
"latitude": "52.514818",
"longitude": "13.356101",
"additionalData": "xyc"
}
it returns a string instead of an object. I therefore cannot parse it like: req.body.latitude and get the value for the latitude.
"----------------------------641080260577727375179249\r\nContent-Disposition: form-data; name=\"file\"; filename=\"Berlin.json\"\r\nContent-Type: application/json\r\n\r\n{\n \"latitude\": \"52.514818\",\n \"longitude\": \"13.356101\",\n \"additionalData\": \"xyc\"\n}\n\r\n----------------------------641080260577727375179249--\r\n"
The issue you have, is that you are sending your API form data and expecting it to behave like JSON.
The easiest solution would be to send the actual JSON in the POST body, in which case your existing code will work.
Otherwise you will just have to grab the JSON from the existing string.
var ApiBuilder = require('claudia-api-builder'), api = new ApiBuilder();
module.exports = api;
api.post('/upload', (req, res) => {
console.log(req.body); // outputs the form-data as string
var myString = req.body.substring(
req.body.lastIndexOf("{"),
req.body.lastIndexOf("}")+1
);
var myJson = JSON.parse(myString);
console.log(myJson) // outputs a valid JSON object
return myObj;
});