0

So I am trying to get some data from the food-data-central API. In my program I console log the data, but I don't get any results on the console. The only thing I get is an error about Fetch Error

import fetch from "node-fetch"

const params = {
    api_key: <apiKey>,
    query: 'chicken breast raw',
    dataType: ["Survey (FNDDS)"],
    pagesize: 5,
}

const api_url = `https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${encodeURIComponent(params.api_key)}&query=${encodeURIComponent(params.query)}&dataType=${encodeURIComponent(params.dataType)}&pageSize=${encodeURIComponent(params.pagesize)}`

function getData(){
    return fetch(api_url).then(response => response.json())
}

getData().then(data => {
    const foods = data.foods[0];
    console.log("Protein: ");
    console.log(foods.foodNutrients[0].value);

    console.log("Fats: ");
    console.log(foods.foodNutrients[1].value);

    console.log("Carbs: ");
    console.log(foods.foodNutrients[2].value);
});

The output that I get:

reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
                   ^
FetchError: request to https://api.nal.usda.gov/fdc/v1/foods/search?api_key=3Bi6rNu3MiTYMaPwMf2u5vs1xAtdKS0n5HoFpgy9&query=chicken%20breast%20raw&dataType=Survey%20(FNDDS)&pageSize=5 failed, reason: connect ETIMEDOUT 2600:1f12:18a:7d00:217:68d:2c2:3718:443
    at ClientRequest.<anonymous> (/home/dflorian251/Desktop/node_modules/node-fetch/lib/index.js:1505:11)
    at ClientRequest.emit (node:events:513:28)
    at TLSSocket.socketErrorListener (node:_http_client:481:9)
    at TLSSocket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT'

Is something wrong with the node-fetch module ?

  • You tried to hide your API KEY but anyway you showed it to us in your error section... `FetchError: request to https://api.nal.usda.gov/fdc/v1/foods/search?api_key=!!!!!!` – Sergey Sosunov Feb 12 '23 at 16:54

0 Answers0