Home > front end >  Data from usda.gov ends in TypeError: response.data.foods is not iterable
Data from usda.gov ends in TypeError: response.data.foods is not iterable

Time:11-30

I am trying to get food data in JavaScript from an API (see https://fdc.nal.usda.gov/api-guide.html).

This is my script:

`

"use strict"

const axios = require('axios')

axios.get("https://api.nal.usda.gov/fdc/v1/foods/search/", {
    params: {
        api_key: "<MY API_KEY>",
        query: "Apple"
    }
}).then(function(response) {

    for (const food of response.data['foods']) {
        console.log(food['fdsId']   ": "   food['description'])
    }

}).catch(function (error) {
    console.log(error);
})

`

After I run this in node, I get "TypeError: response.data.foods is not iterable".

To solve the problem I wanted to console.log(response.data what led to a non-readable output in my console (I work with Visual Studio Code).

Can anyone give me a tip?

Best wishes,

Christian

CodePudding user response:

It looks like browsers are sending headers and/or compensating for responses which Axios is not. So the response isn't JSON, but... something else.

This appears to be a problem with Axios. And it might only occur on some APIs, not all. Adding request headers for Accept and/or Accept-Encoding seems to correct it. For example this is now working for me:

axios.get("https://api.nal.usda.gov/fdc/v1/foods/search/", {
  params: {
    api_key: "<MY API_KEY>",
    query: "Apple"
  },
  headers: {
    'Accept-Encoding': 'application/json'
  }
})
  • Related