我的api请求没有返回任何内容,也没有错误消息

时间:2017-08-05 17:06:22

标签: javascript fetch-api

当我运行这个文件时,我什么都没得到。如果我在最后运行console.log(getInfo());,我会得到Promise <pending>。请帮忙。

function getInfo(){
    var url = `https://api.nutritionix.com/v1_1/search/cheddar%20cheese?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=${apiId}&appKey=${apiKey}`;
    return(
    fetch(url)
    .then(data=>{

        return JSON.parse(data);
     })
    );
}

getInfo().then(result =>{
    console.log(result);

1 个答案:

答案 0 :(得分:3)

这不是您使用fetch API的方式。像这样使用response.json()(记录错误,因为我不知道apiIdapiKey):

function getInfo(){
  var apiId = 1;
  var apiKey = 1;
  var url = `https://api.nutritionix.com/v1_1/search/cheddar%20cheese?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=${apiId}&appKey=${apiKey}`;
  return fetch(url).then(response => response.json());
}

getInfo().then(data => console.log(data));