[Fixed] JavaScript fetch() with JSON parameter

Issue

I’m attempting to request nutrients from the Edamam Food Nutrition api using Node.JS. They provide this example using curl curl -d @food.json -H "Content-Type: application/json" "https://api.edamam.com/api/food-database/v2/nutrients?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"

I’ve successively fetched data from their Food Database API where the only parameter is a URL. This one is requires a JSON with the URL. I’ve hard coded a JSON to correctly call the API. The response I get is

{
"error": "bad_request",
"message": "Entity could not be parsed"
}

What needs to be changed to get a good response?

const url = 'https://api.edamam.com/api/food-database/v2/nutrients?app_id=' + nutrition_app_id + '&app_key=' + nutrition_app_key;
var myFood = '{"ingredients": [ { "quantity": 2, "measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_ounce", "foodId": "food_akjf74ibll2id8aqb8xbha4t4axl"} ]}';

    postData(url, myFood, res)
        .then((data) => {
            res.send(data);
        })
        .catch((error) => console.log(error));

Here is the postData() function

async function postData(url = '', data, res) {
    console.log(data);
    const response = await fetch(url, {
        method: 'POST',
        cache: 'no-cache',
        credentials: 'same-origin',

        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });
    return response.json();
}

Solution

Your data myFood already is a JSON string, then no need to cast it to string with JSON.stringify(data) in postData function.

A simple way to fix this issue – make sure the data object always be a JSON object.

var myFood = {
  "ingredients": [
    {
      "quantity": 2,
      "measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_ounce",
      "foodId": "food_akjf74ibll2id8aqb8xbha4t4axl",
    },
  ]
}; // object instead of string

Leave a Reply

(*) Required, Your email will not be published