0

When I make a POST request to a website, the JSON response body posts 'undefined'. However, it correctly prints the response body content in the form of name/value pair objects to the console when I call console.log(body).

Why is the body 'undefined' when I post the content to the website?

Response body:

  const options = {
    method: 'GET',
    url: 'https://url.com',
    content: {count: '3'},
    headers: {}
  };

Calls to body:

request(options, function (error, response, body) {
    if (error) throw new Error(error);
    console.log(body);
  });

const params = {
    status: request.body
}

M.post('statuses', params) => {
        console.log(params.request);
    };
  • What is `request` in your code? And `M`? – Ivar Jun 30 '22 at 11:23
  • @Ivar 'request' is the function in the code above, initialised here `var request = require('request');`, M is a constant: ```const M = new Mastodon({_code_}) ``` – llleyylllla Jun 30 '22 at 11:51
  • Without more context it is hard to answer. `body` in your request is a parameter that only exists inside of that function. Outside of it it is not accessible. There is also [the issue of asynchronous execution](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) that many walk into. But without a [mcve], it is hard to help you any further. – Ivar Jun 30 '22 at 12:17
  • @Ivar that makes sense, thanks for the response. I think I will just have to go back and amend the code further – llleyylllla Jun 30 '22 at 13:51

0 Answers0