Event.body returns '[object Object]'

I get ‘[object Object]’ in the event.body and don’t know how to solve that

require("dotenv").config();
const mongoose = require("mongoose");
const User = require("../server/models/user");

exports.handler = async (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;

  await mongoose.connect(
    `mongodb+srv://[inset full link]mongodb.net/flashcard?retryWrites=true&w=majority`,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  );

  try {

    const user = await User.findOne({
      email: "bbbb",
    });
    if (!user) {
      await User.create({
        name: 'llll'
      });
    }
    return {
      statusCode: 200,
      status: "ok",
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
        "Access-Control-Allow-Headers":
          "X-Token, append,delete,entries,foreach,get,has,keys,set,values,Authorization",
        "Access-Control-Allow-Credentials": "true",
         "Content-Type": "application/json",
       // "Content-Type": "application/x-www-form-urlencoded",
        "Access-Control-Max-Age": "2592000",
      },
      body: JSON.stringify({ name: 'name updates correctly' }), //=> when hardcoded
//body: {name: event.body.name} //=> name does not update correctly when read from the frontend
    };
  } catch (err) {
    return {
      statusCode: 500,
      body: JSON.stringify({ msg: err.message }),
    };
  }
}

This is what I get back if I console.log the event property

{
  path: '/.netlify/functions/addtask',
  httpMethod: 'POST',
  queryStringParameters: {},
  multiValueQueryStringParameters: {},
  headers: {
    'x-forwarded-for': '::ffff:127.0.0.1',
    connection: 'close',
    host: 'localhost:8888',
    'content-length': '379',
    'accept-encoding': 'gzip, deflate',
    'user-agent': 'vscode-restclient',
    'client-ip': '127.0.0.1'
  },
  multiValueHeaders: {
    'x-forwarded-for': [ '::ffff:127.0.0.1' ],
    connection: [ 'close' ],
    host: [ 'localhost:8888' ],
    'content-length': [ '379' ],
    'accept-encoding': [ 'gzip, deflate' ],
    'user-agent': [ 'vscode-restclient' ],
    'client-ip': [ '127.0.0.1' ]
  },
  body: '[object Object]',
  isBase64Encoded: true,
  rawUrl: 'http://localhost:8888/.netlify/functions/addtask',
  rawQuery: ''
} event here

This is how my frontend looks like


   const response =  await fetch(`https://cool-gnome-d84e5e.netlify.app/.netlify/functions/addtask`, {
      method: 'POST',
      mode: 'cors',
      statusCode: 200,
      status:"ok",
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
        "Access-Control-Allow-Headers": "X-Token, append,delete,entries,foreach,get,has,keys,set,values,Authorization",
        "Access-Control-Allow-Credentials": "true",
         "Content-Type":"application/json",
        //"Content-Type": "application/x-www-form-urlencoded",
        "Access-Control-Max-Age": "2592000",
      },
      body: name
    })

Basically I can not ready from the body as it always give me ‘[object Object]’

I tried

console.debug(event.body) //=> [object Object]
console.debug(JSON.stringify(event.body)) //=> '[object Object]'

Which all did not help. Thanks for reading!

Have you tried parsing your events’ body?

console.debug(JSON.parse(event.body));
1 Like

Hi Tom, thanks for your answer. I actually tried parsing the event’s body before and got this error here

SyntaxError: Unexpected token o in JSON at position 1

Here is the deployed app:

and the repo:

hey there SomeSome, this seems like a Netlify specific issue - [Object object] is a very common search term with millions of search results, so while I’ll leave this thread open, you might get a faster response in a forum more dedicated to general programming advice, as opposed to Netlify specific support. :+1:

Could you change the body: JSON.stringify({ name: 'name updates correctly' }), to use the event body so I can hit the function with a couple of requests?