Search code examples
node.jstypescriptazureazure-functionsazure-http-trigger

TypeScript Azure Function Read Body of POST method as JSON


I have TypeScript azure function with the Http trigger. I am using POST method and sending body to the azure function. But I can not read, request body data as Javascript Object.

My function code

import { AzureFunction, Context, HttpRequest } from "@azure/functions"

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    context.log('HTTP trigger function processed a request.');
    const name = (req.query.name || (req.body && req.body.name));

    if (name) {
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Ar Item search " + (req.query.name || req.body.name)
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
};

export default httpTrigger;

Postmen request enter image description here

Debug data enter image description here

As the above image body is not a Json object as normal http post request body. It is a string as

name=Janith&age=25 I can not read req.body.name as sample code. I need it to read as

{
  "name":"Janith",
  "age":25
}

My function.json

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "scriptFile": "../dist/ARItemSearch/index.js"
}

Solution

  • You need to use raw option within postman's body tab and then pass a json as follows-

    {
      "name":"Janith",
      "age":25
    }
    

    Then you will be able to retrieve json object using req.body in your function.

    Please refer to this doc for more information on how to pass raw json into a request using postman.