2017-09-04 62 views
1

我正在使用Yelp API(通过向其请求使用https://cors-anywhere.herokuapp.com/作为代理 - 因为Yelp API本身不支持CORS)尝试创建与Yelp非常相似的应用寻找我自己的做法。我能够在浏览器的控制台中获得响应。响应中有一个名为business的阵列,其中的商业符合搜索条件。我正在尝试使用.(map)来映射企业数组。但是,我不断收到Cannot read property 'map' of undefined尝试映射Yelp API repsonse

我从Yelp API收到的回复如下。谢谢 Yelp API Response Image

此外,如果有任何关于JavaScript的其他提示,想到我的代码时想到的,请分享,因为我很早就进入了我的编程生涯。

const Yelp = { 
    getAccessToken: function() { 
    if(accessToken) { 
     return new Promise(resolve => resolve(accessToken)); 
    }; 
    return fetch(accessTokenUrl, { 
     method: 'POST' 
    }).then(response => response.json()).then(jsonResponse => { 
    accessToken = jsonResponse.access_token; 
    }) 
    }, 

    search: function(term,location,sortBy) { 
    return this.getAccessToken().then(() => { 
     const yelpRetrieveUrl = `${corsAnywhereUrl}https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}&sort_by=${sortBy}`; 
     return fetch(yelpRetrieveUrl, { 
     headers: {Authorization: `Bearer ${accessToken}`} 
    }); 
    }).then(jsonResponse => { 
    if(1 > 0){ 
    console.log('true!!!!'); 
    return jsonResponse.businesses.map(business => { 
     return { 
     id: business.id, 
     imageSrc: business.image_url, 
     name: business.name, 
     address: business.location.address1, 
     city: business.location.city, 
     state: business.location.state, 
     zipCode: business.location.zip_code, 
     category: business.categories, 
     rating: business.rating, 
     reviewCount: business.review_count 
     }; 
    }); 
    } else { 
    console.log('FALSE') 
    } 

    }) 
} 

}; 
+0

考虑接受解决的答案? – Kyon

+0

谢谢你提到这一点,我没有意识到我需要接受一个答案。 –

回答

0
fetch(myRequest).then(function(response) { 
    var contentType = response.headers.get("content-type"); 
    if(contentType && contentType.includes("application/json")) { 
     return response.json(); 
    } 
    throw new TypeError("Oops, we haven't got JSON!"); 
    }) 
    .then(function(json) { /* process your JSON further */ }) 
    .catch(function(error) { console.log(error); }); 

你可能搜索jsonResponse#json功能把你的JSON数据集中到一个真正的对象,你可以在JavaScript处理。

因为你问它:当你正在使用的承诺,利用Promise#Catch函数来处理即将到来的错误。不要让浏览器处理它们,因为它们在不同的浏览器中可能有不同的行为。

并可能删除1> 0检查,因为它总是如此,但我认为这只是为了测试目的。

我希望我能帮助你!因为我目前在移动设备上,所以我可能会在后面添加代码。