Javascript 如何从promise获得JSON
代码:Javascript 如何从promise获得JSON,javascript,json,react-native,Javascript,Json,React Native,代码: fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, { method: "GET", headers : { 'Content-Type': 'applicatio
fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, {
method: "GET",
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => {
console.log(response.json())
})
Promise {_40: 0, _65: 0, _55: null, _72: null}
输出:
fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, {
method: "GET",
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(response => {
console.log(response.json())
})
Promise {_40: 0, _65: 0, _55: null, _72: null}
添加另一个,然后:
fetch(...).then(resp => resp.json()).then(data => ...)
请注意,fetch
只会在网络错误上出错,如果您希望它拒绝承诺,例如500响应,您必须检查状态代码并抛出:
fetch(url)
.then(resp => {
// you'll need to supply the function that checks the status here
if (http_response_ok(resp.status)) {
return resp.json();
} else {
throw new Error(`Got back ${resp.status}`);
}
}).then(data => {
// happy path
}).catch(err => {
// sad path
});
添加另一个,然后:
fetch(...).then(resp => resp.json()).then(data => ...)
请注意,fetch
只会在网络错误上出错,如果您希望它拒绝承诺,例如500响应,您必须检查状态代码并抛出:
fetch(url)
.then(resp => {
// you'll need to supply the function that checks the status here
if (http_response_ok(resp.status)) {
return resp.json();
} else {
throw new Error(`Got back ${resp.status}`);
}
}).then(data => {
// happy path
}).catch(err => {
// sad path
});
您可以等待答复:
fetch(url, options).then(async (response) => {
const data = await response.json();
console.log(data)
})
您可以等待答复:
fetch(url, options).then(async (response) => {
const data = await response.json();
console.log(data)
})
然后添加另一个:
fetch(…)。然后(resp=>resp.json())。然后(data=>…)
为什么要在GET
请求中发送Content-type
头?您不使用GET
发送任何内容。然后添加另一个:fetch(…)。然后(resp=>resp.json())。然后(data=>…)
为什么要在GET
请求中发送内容类型
头?您没有使用GET
发送任何内容。GET-from:可能的未处理承诺拒绝(id:0):@SalmanGhumsani添加捕获处理程序,请参阅我的更新答案。GET:console.log(“sad-path”)请参阅以获取有关该响应的信息warning@SalmanGhumsanidoconsole.log(错误)代码>您应该可以看到实际错误。获取自:可能的未处理承诺拒绝(id:0):@SalmanGhumsani添加捕获处理程序,请参阅我的更新答案。获取:console.log(“sad路径”)请参阅以获取有关该错误的信息warning@SalmanGhumsanidoconsole.log(错误)代码>你应该看到实际的错误。是的,很酷,这是工作简单,我看起来一样谢谢:)是的,很酷,这是工作简单,我看起来一样谢谢:)