【发布时间】:2021-10-26 21:15:34
【问题描述】:
我显然在这里得到了 HTML,但我不明白为什么。这是预期获取数据并将 URL 解析为 json 的函数,但即使控制台在使用 console.log(res) 时显示 URL,当我尝试 res.json() 时,我也会得到 rejected promise
const fetchData = async () => {
navigator.geolocation.getCurrentPosition(function(position) {
setLat(position.coords.latitude);
setLong(position.coords.longitude);
});
await fetch(`${process.env.REACT_APP_API_URL}/weather?lat=${lat}&lon=${long}&units=metric&APPID=${process.env.REACT_APP_API_KEY}`)
.then(res => console.log(res)) //expected URL appears in the console.
}
fetchData();
}, [lat,long])
我尝试 res.text() 来查看正在获取的响应并>得出结论,我正在从公共目录中获取 HTML 文件。 (考虑到意外的标记,我假设它是 HTML。)我不明白 >为什么它不解析为 JSON,而是获取 HTML。 console HTML info我在控制台中看到了这个,但不知道从这里做什么
我还在应用程序的控制台中检查了 fetch('https://api.openweathermap.org/data/2.5/weather?lat=28.052684799999998&lon=-82.427904&APPID=d8c1409b5342d12f52e6dce35fc26aac') 并返回了一个未决的承诺。 console results
我上传了repo以便更好地理解 是否因为环境变量而发生一些混乱?
【问题讨论】:
-
返回的数据不是 JSON。它不是 JSON。
-
navigator.geolocation.getCurrentPosition(function(position) { setLat(position.coords.latitude); setLong(position.coords.longitude); });是异步的......你的 lat 和 lng 不会被设置 -
在控制台写
fetch(url).then(response => response.text()).then(console.log)查看响应。它说响应以<开头,因此它很可能是 XML 或 HTML,而不是 JSON。一种可能的解释是 API 默认提供 XML,而您忘记添加Accept: application/json标头。不过,console.logging 响应应该会告诉你出了什么问题。
标签: javascript reactjs environment-variables fetch-api