Javascript 如何从响应中获取实际数据?我没有定义
我试图从yelp api获取数据 我有一个抓取函数,如下所示:Javascript 如何从响应中获取实际数据?我没有定义,javascript,http,fetch,Javascript,Http,Fetch,我试图从yelp api获取数据 我有一个抓取函数,如下所示: export function fetchRestaurants (term) { const endpoint = `businesses/search?term=${term}&location=NYC` return fetch(endpoint, { headers: new Headers({ 'Authorization': 'Bearer '+'oSJvaTmFtY
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
})
}
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
第一个然后的响应是200
,如下所示:
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
})
}
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
但是我尝试在第二个上对它执行.json
,然后,当我尝试记录它时,它是未定义的
关于如何获得实际数据有什么想法吗?
感谢第一个。然后回调函数需要返回res.json()
像这样:
.then((res) => {
console.log(res)
return res.json()
})
第一个。然后回调函数需要返回res.json()
像这样:
.then((res) => {
console.log(res)
return res.json()
})
这回答了你的问题吗@HereticMonkey-不,因为问题说,数据在第二次then()
回调中未定义。返回res.json()@EugenSunic之前检查错误-他们没有返回res.json()
,这就是错误。@Quentin即使返回res.json()
,的返回值
仍将是未定义的
,重复项将适用。这是否回答了您的问题@HereticMonkey-不,因为问题说,数据在第二次then()
回调中未定义。返回res.json()@EugenSunic之前检查错误-他们没有返回res.json()
,这就是错误。@Quentin即使返回res.json()
,data
的返回值仍将是undefined
,并且将应用重复项。否,因为在我的示例中称为data
的第二个值未定义。。所以我不能在未定义的情况下调用.json。@giorgiomartini-数据
在第二个中未定义,然后
,因为您没有从第一个然后
返回任何内容(这个答案告诉您更正).那是因为您在承诺链的上一次回调中没有返回任何内容…@silencedogood如果您编辑您的答案,说我需要在第一次回调时返回值,那么我将接受它,,thx@giorgiomartini-其中包含res.json
。第一个包含res.json
。第二个没有。它表明它已经在谈论第一个,然后是
。否,因为在我的示例中称为data
的第二个未定义。。所以我不能在未定义的情况下调用.json。@giorgiomartini-数据
在第二个中未定义,然后
,因为您没有从第一个然后
返回任何内容(这个答案告诉您更正).那是因为您在承诺链的上一次回调中没有返回任何内容…@silencedogood如果您编辑您的答案,说我需要在第一次回调时返回值,那么我将接受它,,thx@giorgiomartini-其中包含res.json
。第一个包含res.json
。第二个没有。它表明它已经在谈论第一个,然后是。