Home > OS >  How to access post object from http request using nodejs
How to access post object from http request using nodejs

Time:04-23

The simple version of my question is: How can I get access to the hello world part of this object: { '{"msg":"Hello World!"}': '' }

The longer and introductionary version is; I've been trying to send and receive postBody objects, but I can't seem to access the data from the request i've sent.

I think I'm missing something simple, I recreated a request from here, but I can't seem to access the "hello world" part of the body.

An answer as to how to access the inner object, and optional tips and/or pointers would be greatly appreciated.

Post request:

var postData = JSON.stringify({ msg: "Hello World!" });
  var options = {
    hostname: "localhost",
    port: 5000,
    path: "/tester",
    method: "GET",
    headers: {
     "Content-Type": "application/x-www-form-urlencoded",
     "Content-Length": postData.length,
    },
  };
  var req = http.request(options, (res) => {
    console.log("statusCode:", res.statusCode);
    console.log("headers:", res.headers);
    res.on("data", (d) => {
      // console.log("d", d)
      process.stdout.write(d);
    });
  });
  req.on("error", (e) => {
    console.error(e);
  });
  req.write(postData);
  req.end();

Receive request:

app.get("/tester", (req, res) => {
  console.log("request fired");
  console.log("body:", req.body);
  let x = req.body
  console.log(typeof x);
  res.end();
});

log:

request fired
body: { '{"msg":"Hello World!"}': '' }
object

CodePudding user response:

You are doing JSON.stringify when you are sending the data. So when you receive it just parse it using JSON.parse. Something like this

let data = JSON.parse(req.body);

Now you can access msg from your body like this

console.log(data.msg);

This will return Hello World!

Your case seems to be weird in your case for some reason your data is in the key of the object you can access data like this

let data = {'{"msg":"Hello World!"}': ''}

console.log(JSON.parse(Object.keys(data)[0]).msg)

let stringifiedData = JSON.stringify({
  msg: "Hello World!"
});

console.log(stringifiedData);

let parsedData = JSON.parse(stringifiedData);

console.log(parsedData.msg);

/* UPDATE */

let data = {
  '{"msg":"Hello World!"}': ''
}

console.log(JSON.parse(Object.keys(data)[0]).msg)

  • Related