i've asked very similar question before (Why is it when posting an object into a json file, one of the key/value always appears as curly braces?), and hate asking it again but i can´t find the answer anywhere. So i have this function that returns "hello" (it should return a certain value, but error happens either way, so i have "hello" for testing).
function index(){
return new Promise((resolve, reject) => {
setTimeout(() => {
$("#noteDisplay").on("click", ".remove", (e) => {
//indexResult = (e.currentTarget.parentNode.id - 1);
const indexResult = "hello";
let error = false;
//-----
if(!error){
resolve(indexResult);
} else {
reject('Something went wrong!');
}
});
}, 2000);
});
}
I´m calling this function here.
export default function SendId(){
React.useEffect(() => {
/*$("#noteDisplay").on("click", ".remove", async (e) => {
console.log("ola");
});*/
//-----------------------------------------------------
$("#noteDisplay").on("click", ".remove", async (e) => {
const PORT = process.env.PORT || 3001;
let index_note = { // the object
index: await index()
}
let data = JSON.stringify(index_note);
let xhr = new XMLHttpRequest();
xhr.open('POST', `http://localhost:${PORT}/api/1`, true);
xhr.send(data);
console.log("the data was sent")
});
});
return(null);
}
And with or without async await it always retuns curly braces, when i log it. I console.log it this way(but i don't think that's the problem).
app.post("/api/:1", (req, res) =>{
console.log(req.body);
});
Sorry for the repeating question, and any help would be appreciated.
You are not added 'Content-Type': 'application/json' to your request headers. Maybe this is an issue
xhr.setRequestHeader('Content-Type', 'application/json');