【问题标题】:Error: Unexpected token < in JSON at position 0错误:位置 0 处的 JSON 中的意外标记 <
【发布时间】:2021-07-28 04:28:29
【问题描述】:

我知道这是一个典型的错误,但我无法弄清楚,问题出在哪里?浏览器中的链接以 JSON 结构正常打开,但在weatherRequest.json() 中我什至收到错误Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 0

请帮忙...

let fetchWeather = async () => {
    const weatherRequest = await fetch(`api.openweathermap.org/data/2.5/forecast?q=München,DE&appid=my_key`);
    const weatherStore = await weatherRequest.json();
    console.log('weatherStore', weatherStore);
}

fetchWeather();

【问题讨论】:

  • 您在第 2 行的字符串周围使用了错误的引号...使用 '(单引号)而不是 `(反引号)
  • @panther 这没有任何意义。
  • 获取 JSON 的结果是否正确?
  • 你的url需要https。
  • api.openweathermap.org/data/2.5/forecast?q=München,DE&amp;appid=my_key 是相对路径,所以前面会加上当前域。因此,您将从您的域请求该路径,这很可能会返回一个 html 错误页面。该错误页面以&lt; 开头。您需要写//api.openweathermap.org/data/2.5/forecast?q=München,DE&amp;appid=my_keyhttp://api.openweathermap.org/data/2.5/forecast?q=München,DE&amp;appid=my_keyhttps://api.openweathermap.org/data/2.5/forecast?q=München,DE&amp;appid=my_key

标签: javascript json async-await


【解决方案1】:

这发生在我身上。两个修复帮助我解决了这个问题。

  1. 使用axios 而不是fetch。 (不知道为什么 fetch 没有帮助)

安装 -> npm install axios

使用 -> import axios from 'axios';

  1. https://作为前缀的api url就像这样https://api.openweathermap.org...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 2017-10-21
    • 2018-01-29
    • 1970-01-01
    • 2021-10-22
    • 2021-12-21
    相关资源
    最近更新 更多