0
votes

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"
}
2
any reason why you chose the later answer?Sajeetharan

2 Answers

2
votes

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.

1
votes

I think you just need to use the req.body directly and validate against your schema before storing it,

const {error, schema} = await validate(User, req.body);

Also i noticed one thing on the POSTMAN, you need to use raw and send it as a JSON object instead of sending it as a request parameter.