I’m writing a program which sends a small piece of JSON data from a page to a server. Whenever I run the code and send the data, trying to read it on the server side just shows it as ‘[object Object]’
Here’s my server side code for reading this specific request
async function serve(request, response){var requestURL = new URL(request.url, https://${request.headers.host})var path = requestURL.pathname;
req = ""
request.on("data", (data)=>{
req += data;
})
request.on("end", ()=> {
console.log(JSON.stringify(req));
})
}
Then here’s my client side
const response = await fetch("./login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({name: "John Doe"})
});
}
There are a few similar issues like this already, but they’re all either for people using Express, which I am not using, or people trying to send larger requests than a tiny JSON object.
I’ve tried sending it in a few different formats, as a string, changing the structure of the object, reading it as a string on the server side, concatenating it while logging to the console, etc.
What can I do to fix this problem?
2
Answers
On this line:
req += data;
you add thereq
variable (which is a string) to thedata
object.In JavaScript an when you concatenate an
Object
with a string, JavaScript will call thetoString
method on the object, and therefore return[object Object]
so
req += data
is the same asreq += data.toString()
anddata.toString()
returns[object Object]
If you want to merge the objects, you can do that with the Object.assign()
Use
JSON.parse()
instead ofJSON.stringify
on the within the request’s data end event.