我之前的问题不够清晰,所以我会尽量说清楚。我正在尝试创建一个天气应用程序,但是每次我尝试fetch信息(JSON格式)时,它都返回未定义。我使用的是纯JavaScript,并试图加载Open Weather Map的API。我尝试使用另一个API (自由天气API),但同样返回未定义。请注意,网站加载正常,我认为这只是我的代码的问题。
fetch('http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric').then(function (response) {
console.log('success!', response.main);
}).catch(function (err) {
console.warn('Something went wrong.', err);
});发布于 2020-12-28 15:15:19
promise的工作方式是,您需要转换响应并将此转换传递到下一个then管道。
fetch(
'http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric'
)
.then(function (response) {
return response.json();
})
.then(function (responseJSON) {
console.log('success!', responseJSON.main);
})
.catch(function (err) {
console.warn('Something went wrong.', err);
});说明:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
发布于 2020-12-28 15:33:29
在对数据进行任何操作之前,我们应该在response对象上使用json()方法。实际上,json()方法接受一个响应流,并读取它直到完成。它返回一个承诺。因此,为了使用response.json()返回的promise,我们应该使用.then()方法。在解析它时,将主体文本解析为JSON。
fetch('http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric')
.then(function (response) {
// parsing the body of response object
return response.json();
})
.then(function (response) {
console.log('sucess', response.main);
})
.catch(function (err) {
console.warn('Something went wrong.', err);
});https://stackoverflow.com/questions/65473835
复制相似问题