0

I'm sending a POST request to an external API which returns a JSON response. But I'm unable to access the JSON property it comes out as undefined however when I print the whole body the property exists. I have tried cloning the body to a new variable but it didn't work. Also tried parsing the JSON again but it didn't work either.

request.post({url:`http://2captcha.com/in.php?key=${key}&method=${service}&sitekey=${sitekey}&pageurl=${pageurl}&json=${json}`}, function(error, response, body){
                   if (response.statusCode == 200) {
                       console.log(body);
                       console.log(body.status);
                       console.log(body.request);
                   }

My console

{"status":1,"request":"67055353796"}
undefined
undefined
neo81040
  • 23
  • 6
  • The problem is in code or a setup you aren't showing us, so we might not be able to help you debug this. – Andy Ray May 26 '21 at 19:21
  • 1
    "when I print the whole body the property exists" Where does it exist? You should be able to get the object path by looking. – Siddharth May 26 '21 at 19:21
  • @Siddharth Check the console output please you can see the JSON – neo81040 May 26 '21 at 19:22
  • 2
    `body` is a string, not an object. Otherwise the output would be different. You have to parse the JSON first. – Felix Kling May 26 '21 at 19:22
  • @FelixKling I forgot to mention in the post but I have tried parsing the JSON the result was same also the server already sends the response in JSON. – neo81040 May 26 '21 at 19:25
  • 1
    *"I have tried parsing the JSON"* How did you do that? *"the server already sends the response in JSON"* JSON is a *textual data format*. It has to be *parsed* into a native JavaScript value before you can use it. – Felix Kling May 26 '21 at 19:27
  • @FelixKling I did it via JSON.parse(body) – neo81040 May 26 '21 at 19:28
  • Place a debug breakpoint on the console.log line so that you can check the types, etc using the repl. – Siddharth May 26 '21 at 19:28
  • And what did you do with the return value of `JSON.parse(body)`? Please show exactly what you did. – Felix Kling May 26 '21 at 19:28
  • @FelixKling Sorry I didn't assign a new variable when I tried parsing it assigning a new variable worked. – neo81040 May 26 '21 at 19:33

0 Answers0