【发布时间】:2022-01-22 07:39:53
【问题描述】:
您好,我正在使用 OpenWeatherMap API 测试这个 JS 函数,但是当我获取请求时,promise 会跳转到 .then() 并处于待处理状态,但 API 正在使用 HTML 代码进行响应。
这是我的代码:
function onSearch(city){
fetch(`api.openweathermap.org/data/2.5/weather?q=London&appid=${ApiKey}&units=metric`)
.then(response => response.json())
.then(data => {
console.log(data)
if(data.main !== undefined){
const city = {
min: Math.round(data.main.temp_min),
max: Math.round(data.main.temp_max),
id: data.id,
img: data.weather[0].icon,
wind: data.wind.speed,
temp: data.main.temp,
name: data.name,
logitude: data.coord.lon,
latitude: data.coord.lat
};
}
})
.catch(e => console.log(e))
}
这是 API 响应
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="/manifest.json" />
<!--
Notice the use of in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Weather App</title>
<script defer src="/static/js/bundle.js"></script></head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
实际上这是我的 index.html 代码
关于如何解决这个问题的任何想法?
【问题讨论】:
-
您确定您正在接收有效的 JSON 数据吗?
Unexpected token < ...表示您实际上正在接收 HTML。您可以在开发者工具的网络选项卡中验证这一点。 -
显示错误,因为承诺正在返回
-
<pending>只是承诺的状态(如控制台中所示),但这不是被解析的内容。您可以在网络选项卡中查看请求的实际结果。 -
承诺从未解决,但由于错误而被拒绝。您收到的可能是 HTML 或 XML 而不是 JSON。而不是
response.json()将其(临时)更改为response.text()并查看它记录的内容。 -
所以你想在某处使用组合的
city对象.....?
标签: javascript asynchronous promise openweathermap