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!