【问题标题】:How to fix "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" ERROR如何修复“未捕获(承诺中)语法错误:位置 0 的 JSON 中的意外令牌 <”错误
【发布时间】: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&amp;appid=${Api_Key}`) 试试这个。查看网址前面的//。如果不确定,请使用http://https:// 或仅使用//

标签: javascript reactjs


【解决方案1】:

你得到了一个 JSON。我只是试着打电话

async function get() {
  try {
    const res = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=079b76b390ad70c628a14a9a141e5992`);
    const json = await res.json();
    console.log('json', json)
  } catch (err) {
    console.error('err', err);
  }

}

它的响应是:

{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
  {
"id": 520,
"main": "Rain",
"description": "light intensity shower rain",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 285.3,
"pressure": 1004,
"humidity": 93,
"temp_min": 284.15,
"temp_max": 286.48
},
"visibility": 10000,
"wind": {
"speed": 6.2,
"deg": 90
},
"clouds": {
"all": 90
},
"dt": 1571056651,
"sys": {
"type": 1,
"id": 1502,
"message": 0.0096,
"country": "GB",
"sunrise": 1571034113,
"sunset": 1571073060
},
"timezone": 3600,
"id": 2643743,
"name": "London",
"cod": 200
}

您可能错过了http:// 部分?

【讨论】:

  • 我认为他们拼错了端点,这就是我在回复中最后提到的原因,即缺少http://
  • 你在console.log('json', json)后面漏掉了一个分号
【解决方案2】:

我在我的 Ionic 应用程序中遇到了同样的问题,我只是在 url 之前添加了“./”,它对我有用: fetch('assets/files/data.json') => fetch('./assets/files/data.json')

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2012-10-12
    • 2021-09-23
    • 2014-02-09
    相关资源
    最近更新 更多