【发布时间】:2020-02-11 02:03:54
【问题描述】:
当我尝试从 api(https://openweathermap.org/) 获取数据时,我收到此错误。 Uncaught (in promise) SyntaxError: Unexpected token
这是我的代码。
import React from 'react';
import './App.css';
import Weather from "./components/Weather"
import 'bootstrap/dist/css/bootstrap.min.css'
import 'weather-icons/css/weather-icons.css'
const Api_Key="079b76b390ad70c628a14a9a141e5992";
class App extends React.Component {
constructor(){
super();
this.state={};
this.getWeather();
}
getWeather= async ()=>{
const api_call = await fetch(
`api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${Api_Key}`,
);
const data = await api_call.json();
console.log(data);
}
render()
{
return (
<div className="App">
<Weather/>
</div>
)
}
}
export default App;
谢谢!
【问题讨论】:
-
您期待 json 数据,但 api 正在返回一些 html。尝试
await api_call.text()查看响应并检查它为什么不返回 json -
const data = await api_call.json();这行抛出错误。删除.json(),然后删除console.log(data),看看你得到的HTML,很确定你会在那里找到一些有用的信息。 -
您是否在开发者控制台中检查了请愿书和您收到的请求?似乎你没有得到正确的 json
-
您可以检查浏览器开发者工具中的 Network 选项卡,了解您得到的响应。
-
const api_call = await fetch(`//api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${Api_Key}`)试试这个。查看网址前面的//。如果不确定,请使用http://、https://或仅使用//。
标签: javascript reactjs