Netlify functions unexpected token error while using JSON.parse on post data

465 Views Asked by At

I am checking out Netlify functions and currently trying to implement POST requests. This is the code for netlify function:

export async function handler(event, context) {

    const bodyParsed = JSON.parse(event.body);

    return {
      statusCode: 200,
      body: JSON.stringify({
          bodyParsed: bodyParsed
        })
    };
  }

This is the error I get:

Function invocation failed: SyntaxError: Unexpected token n in JSON at position 1

Now if I return the unparsed event.body using

export async function handler(event, context) {

    // const bodyParsed = JSON.parse(event.body);

    return {
      statusCode: 200,
      body: JSON.stringify({
          bodyParsed: event.body
        })
    };
  }

This is the response I get:

{"bodyParsed":"{name: \"Test\"}"}

What am I doing wrong?

Thanks.

1

There are 1 best solutions below

0
On

When you are making the request use :

{
   "name":"Test"
}

instead of :

{
   name: "Test"
}