【问题标题】:Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0
【发布时间】:2021-03-02 16:39:03
【问题描述】:

我制作了一个小的 vanilla javascript 代码来获取 api,但它抛出错误“未捕获(承诺中)SyntaxError:位置 0 处 JSON 中的意外令牌 N”。我不明白为什么会发现错误。有人可以帮我解决这个问题吗?

const config = {
  url: "https://randomuser.me/",
  numberCards: 24
};

fetch(`${config.url}&amount=${config.numberCards}`)
  .then(function(response) {
    return response.json();
  })
  .then(function(apiResponse) {
    // Output API response to console to view.
    console.log(apiResponse);
  });

【问题讨论】:

  • 你得到什么回应?
  • main.js:7 GET randomuser.me/%20&%20amount%20=24 404 (Not Found) and Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0
  • 好吧,Not found 不是有效的 JSON,因此无法解析。您需要先检查响应是否真正成功。
  • 状态:200(OK)时间:42 ms 它实际上是在访问 API 并显示响应.....但是每当我尝试时,我都会遇到未捕获(承诺)错误
  • 在这种情况下,该 API 是愚蠢的,并返回一个“成功”,其中包含一条错误消息。如果 API 在您的控制之下,您应该更改它。如果不是...我想您必须在尝试解析之前过滤掉类似的错误消息。

标签: javascript promise fetch-api


【解决方案1】:

正因为如此。

const config = {
  url: "https://randomuser.me/",
  numberCards: 24
};

fetch(`${config.url}&amount=${config.numberCards}`)

应该是,

const config = {
  url: "https://randomuser.me/api/",
  numberCards: 24
};

fetch(`${config.url}?amount=${config.numberCards}`)

这是因为 json 数据来自“https://randomuser.me/api/”。不是“https://randomuser.me/”。并且查询字符串必须以“?”开头标记。 “&”标记用于分隔查询字符串。 (比如这个“https://example.com/?amount=24&hi=en”)

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 2020-03-26
    • 2019-08-14
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2021-12-21
    相关资源
    最近更新 更多