我知道这将是一个非常愚蠢的问题,但我一直在努力解决这个问题。我从正在使用的 API 收到以下响应:
{
"item_id": "51c3d78797c3e6d8d3b546cf",
"item_name": "Cola, Cherry",
"brand_id": "51db3801176fe9790a89ae0b",
"brand_name": "Coke",
"item_description": "Cherry",
"updated_at": "2013-07-09T00:00:46.000Z",
"nf_ingredient_statement": "Carbonated Water, High Fructose Corn Syrup and/or Sucrose, Caramel Color, Phosphoric Acid, Natural Flavors, Caffeine.",
"nf_calories": 100,
"nf_calories_from_fat": 0,
"nf_total_fat": 0,
"nf_saturated_fat": null,
"nf_cholesterol": null,
"nf_sodium": 25,
"nf_total_carbohydrate": 28,
"nf_dietary_fiber": null,
"nf_sugars": 28,
"nf_protein": 0,
"nf_vitamin_a_dv": 0,
"nf_vitamin_c_dv": 0,
"nf_calcium_dv": 0,
"nf_iron_dv": 0,
"nf_servings_per_container": 6,
"nf_serving_size_qty": 8,
"nf_serving_size_unit": "fl oz",
}
这是我试图运行的代码:
var rp = require('request-promise');
module.exports = {
getIngredients: function(req, callback) {
rp({
method: 'GET',
uri: `https://api.nutritionix.com/v1_1/item?upc=${req.body.upc}&appId=${process.env.NUTRITIONIX_APP_ID}&appKey=${process.env.NUTRITIONIX_APPP_KEY}`
}).then((data) => {
console.log(`Talked to NutritionixAPI, result was: ${data}`);
var ingredients = data.nf_ingredient_statement.split(',');
console.log(`Ingredients split from the data are: ${ingredients}`);
return callback(ingredients);
}).catch((err) => {
console.log(`Error occured in NutritionixAPI, ${err}`)
return callback(Object.assign({}, err, { error: true }));
});
}
}
我想弄清楚为什么data
会正确打印到控制台,但是一旦我尝试访问内部的任何值,我就会得到它的错误undefined
。我也尝试过 JSON 中的其他值,因此非常感谢您的帮助!
编辑:我想澄清问题是什么,这与回调和异步调用无关,因为它们完美地工作。我的问题特别是var ingredients = data.nf_ingredient_statement.split(',');
where nf_ingredient_statement
is undefined 即使显然不是。