API response body returns undefined instead of expected data

I’m working with a weather cameras API through RapidAPI and having trouble getting the response data. I’ve got my project set up with Node.js and the unirest library for making HTTP requests.

The weird thing is that when I make the API call, I can see the response headers just fine, but the response body comes back as undefined. I should be getting a JSON object with camera data, but instead I get nothing.

Here’s my current code:

const unirest = require('unirest');

unirest.get("https://cameraapi.p.rapidapi.com/cameras/list/region=EU?language=en&display=cameras%3Aimage%2Cposition")
.header("X-RapidAPI-Key", "API_KEY_HERE")
.end(function (response) {
  console.log(response.status, response.headers, response.body);
});

The status code and headers print correctly, but response.body is always undefined. I’m not sure if this is a JSON parsing issue or something wrong with how I’m using unirest. Has anyone run into this before? Any ideas what might be causing this?

This looks like an async timing issue. Unirest sometimes needs a moment before the body’s ready. Try putting your console.log in a setTimeout with 100ms delay, or just switch to .then() instead of .end(). Also, that URL looks wrong - shouldn’t those query params use & separators instead of being stuck in the path?

I’ve hit this same issue with APIs that don’t return the expected content type. The API might be sending data that unirest can’t auto-parse as JSON. Try adding .header("Accept", "application/json") to your request - this tells the server you want JSON back. Some APIs also need the Content-Type header even on GET requests. Double-check that API endpoint too - the URL structure with those query params looks odd. I’d test the same endpoint in Postman first to see the raw response. If it’s coming back as a string instead of parsed JSON, you can manually parse it with JSON.parse(response.body) as a quick fix while you troubleshoot.

This is a callback parameter issue with unirest. Your callback function should get result as the parameter, not response. Change it to function (result) and access result.body instead. I hit this exact same problem last year when migrating API calls. Unirest’s docs aren’t great about explaining this - the response object structure is different from other HTTP libraries. Also check if that API endpoint actually returns data. Some weather camera APIs have regional restrictions or need extra auth beyond the RapidAPI key. Log the entire result object first to see what properties you actually get.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.