Reputation: 585
I am creating a POST method api end point. I am sending the payload as a JSON string in RAW format from the postman. Then I am doing JSON.parse in my deno app controller. But the output after doing the JSON.parse is still a JSON string.
This is my controller code:
import { IResponse } from '../models/response.ts'
import { IFulllName } from '../models/full-name.ts'
export const printFullName = async (
{ request, response }: { request: any, response: any }) => {
const body = await request.body();
let value = body.value;
console.log(value, '||| value');
console.log(typeof(value), '||| value type');
value = JSON.parse(JSON.stringify(value));
// This should be a JSON object but it still logs as a string
console.log(value, '||| value');
console.log(typeof(value), '||| value type');
}
If I do JSON.parse directly without JSON.stringify, I get a 500 internal server error (no error in the logs as well).
Here is the payload that I have tried:
'{"firstName": "First", "lastName": "Last"}'
Note: I am using oak along with Deno.
What I need is to convert the JSON string into a JSON object in the controller code.
In case there is any inbuilt way of doing so using any oak method, please do suggest.
Upvotes: 2
Views: 1674
Reputation: 40444
You're sending an invalid JSON object, in Postman you should POST:
{"firstName": "First", "lastName": "Last"}
without being wrapped by '
.
const postedJSON = `'{"firstName": "First", "lastName": "Last"}'`;
// Invalid JSON for JSON.parse, remove '
const stringified = JSON.stringify(postedJSON);
console.log(stringified); // a valid JSON string
console.log(JSON.parse(stringified) === postedJSON);
In any case, the correct way to read a JSON payload in Oak
is:
app.use(async ({ request, response }) => {
const result = await request.body();
console.log(result.value)
});
Be sure to send Content-Type: application/json
Upvotes: 2