我正在尝试从 yelp api 获取数据,
我有一个如下所示的获取函数:
export function fetchRestaurants (term) {
const endpoint = `businesses/search?term=${term}&location=NYC`
return fetch(endpoint, {
headers: new Headers({
'Authorization': 'Bearer '+'oSJvaTmFtYVCEJcMsLFA4uRljDOILtEfp0sTWflSWclozapMP1rCZ6uttKPOoYnrdUGcTXI0ztOf3rTPVSBRa1JjngqcoTKD30YUp7yKxhZCNzS4bsZV_DqzzkAwXXYx',
}),
})
.then((res) => {
console.log(res)
res.json()
})
.then((data) => {
console.log(data)
// this is undefined!
return data
})
}
第一个 then
的响应为 200
,如下所示:
Response {type: "basic", url: "http://localhost:3000/businesses/search?term=pizza&location=NYC", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "http://localhost:3000/businesses/search?term=pizza&location=NYC"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: true
但后来我尝试在第二个 then
上对其执行 .json
,当我尝试记录它时,它是未定义的。
关于如何获取实际数据有什么想法吗? 谢谢
最佳答案
第一个.then
回调函数需要返回res.json()
像这样:
.then((res) => {
console.log(res)
return res.json()
})
关于javascript - 如何从响应中获取实际数据?我得到未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60097966/