skip to Main Content

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


  1. On this line: req += data; you add the req variable (which is a string) to the data object.

    In JavaScript an when you concatenate an Object with a string, JavaScript will call the toString method on the object, and therefore return [object Object]

    so req += data is the same as req += data.toString() and data.toString() returns [object Object]

    If you want to merge the objects, you can do that with the Object.assign()

    Login or Signup to reply.
  2. Use JSON.parse() instead of JSON.stringify on the within the request’s data end event.

     console.log(JSON.parse(req));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search