【问题标题】:Unexpected token < in JSON at position 0 with JSON.parseJSON.parse 中位置 0 的 JSON 中的意外令牌 <
【发布时间】:2019-06-09 15:29:43
【问题描述】:

我正在遍历一个对象,并对该对象中的项向 API 发出多个请求,以获取数据然后将其发送到数据库。接收数据时,我使用 JSON.parse() 将 json 存储在一个变量中,并将其发送到处理它的回调,最终将发送到数据库。

在研究了这个问题并在 StackOverflow 上看到了类似的问题之后,考虑到请求中的数据得到了很好的解析,我仍然无法弄清楚我的问题,但我在运行代码几分钟后就遇到了这个问题。

async.forEach(players, function(item, callback) {

        var playerAccountId = (item.accountId).replace(/-/gi, '');
        var kills = item.kills;
        var placement = item.placement;

        let options = {
            url: "https://fortnite-api.theapinetwork.com/prod09/users/public/br_stats_v2?user_id=" + playerAccountId,
            method: 'GET',
            headers: {
                'content-type': 'application/json',
                'Authorization' : 'c825697ee0b871c684332601b46c2b71'
            }
        };

    // -------------------- //

        function requestData(callback) {
            request(options, function(err, res, body) {
                body = body.trim();
                let json = JSON.parse(body);
                let username = json.data.username;
                return callback(username);

            });
        }

        function doSomething(name) { //Send data directly to database from this callback
            //console.log(name);

            var player = {
                "Name": name,
                "Account ID": playerAccountId,
                "Kills": kills,
                "Placement": placement
            }
            console.log(player);

        }
        requestData(doSomething);
    });





在我 console.log 我得到的所有数据之后(考虑到它正在被记录,它正在被正确解析),在我运行我的代码几分钟后,控制台在位置 0 错误的 JSON 中给出了 Unexpected token

注意:我为此 API 创建了另一个帐户,以便其他人可以使用不是我的实际授权 ID 的授权 ID 测试此问题。

通过回调函数传递正文并记录它时出错。

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en-US"> <![endif]-->
<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="en-US"> <![endif]-->
<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en-US"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-US"> <!--<![endif]-->
<head>
<title>fortnite-api.theapinetwork.com | 524: A timeout occurred</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1" />
<link rel="stylesheet" id="cf_styles-css" href="/cdn-cgi/styles/cf.errors.css" type="text/css" media="screen,projection" />
<!--[if lt IE 9]><link rel="stylesheet" id='cf_styles-ie-css' href="/cdn-cgi/styles/cf.errors.ie.css" type="text/css" media="screen,projection" /><![endif]-->
<style type="text/css">body{margin:0;padding:0}</style>
</head>
<body>
<div id="cf-wrapper">
<div id="cf-error-details" class="cf-error-details-wrapper">
<div class="cf-wrapper cf-error-overview">
<h1>
<span class="cf-error-type">Error</span>
<span class="cf-error-code">524</span>
<small class="heading-ray-id">Ray ID: 4e465e6118edcce2 &bull; 2019-06-09 22:00:24 UTC</small>
</h1>
<h2 class="cf-subheadline">A timeout occurred</h2>
</div>
<div class="cf-section cf-highlight cf-status-display">
<div class="cf-wrapper">
<div class="cf-columns cols-3">
<div id="cf-browser-status" class="cf-column cf-status-item cf-browser-status ">
<div class="cf-icon-error-container">
<i class="cf-icon cf-icon-browser"></i>
<i class="cf-icon-status cf-icon-ok"></i>
</div>
<span class="cf-status-desc">You</span>
<h3 class="cf-status-name">Browser</h3>
<span class="cf-status-label">Working</span>
</div>
<div id="cf-cloudflare-status" class="cf-column cf-status-item cf-cloudflare-status ">
<div class="cf-icon-error-container">
<i class="cf-icon cf-icon-cloud"></i>
<i class="cf-icon-status cf-icon-ok"></i>
</div>
<span class="cf-status-desc">Newark</span>
<h3 class="cf-status-name">Cloudflare</h3>
<span class="cf-status-label">Working</span>
</div>
<div id="cf-host-status" class="cf-column cf-status-item cf-host-status cf-error-source">
<div class="cf-icon-error-container">
<i class="cf-icon cf-icon-server"></i>
<i class="cf-icon-status cf-icon-error"></i>
</div>
<span class="cf-status-desc">fortnite-api.theapinetwork.com</span>
<h3 class="cf-status-name">Host</h3>
<span class="cf-status-label">Error</span>
</div>
</div>
</div>
</div>
<div class="cf-section cf-wrapper">
<div class="cf-columns two">
<div class="cf-column">
<h2>What happened?</h2>
<p>The origin web server timed out responding to this request.</p>
</div>
<div class="cf-column">
<h2>What can I do?</h2>
<h5>If you're a visitor of this website:</h5>
<p>Please try again in a few minutes.</p>
<h5>If you're the owner of this website:</h5>
<p><span>The connection to the origin web server was made, but the origin web server timed out before responding. The likely cause is an overloaded background task, database or application, stressing the resources on your web server. To resolve, please work with your hosting provider or web development team to free up resources for your database or overloaded application.</span> <a href="https://support.cloudflare.com/hc/en-us/articles/200171926-Error-524">Additional troubleshooting information here.</a></p>
</div>
</div>
</div>
<div class="cf-error-footer cf-wrapper">
<p>
<span class="cf-footer-item">Cloudflare Ray ID: <strong>4e465e6118edcce2</strong></span>
<span class="cf-footer-separator">&bull;</span>
<span class="cf-footer-item"><span>Your IP</span>: 173.54.204.123</span>
<span class="cf-footer-separator">&bull;</span>
<span class="cf-footer-item"><span>Performance &amp; security by</span> <a href="https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer" id="brand_link" target="_blank">Cloudflare</a></span>
</p>
</div>
</div>
</div>
</body>
</html>

【问题讨论】:

  • 请在尝试解析 http api 响应之前检查错误
  • AFAIK 你不需要使用 JSON.parse ,由于 dataTyp 应该已经解析了

标签: javascript node.js json


【解决方案1】:

在您的请求选项中,您可以这样做:

// add `json: true`, and moved the query string to `qs` to automatically encode
let options = {
    url: "https://fortnite-api.theapinetwork.com/prod09/users/public/br_stats_v2",
    qs: {
        user_id: playerAccountId
    },
    method: 'GET',
    json: true, // add this
    headers: {
        'Authorization' : 'c825697ee0b871c684332601b46c2b71'
    }
};

// removed json parsing and trimming.
function requestData(callback) {
    request(options, function(err, res, body) {
        let username = body.data.username;
        return callback(username);
    });
}

这会自动将响应转换为 JSON 对象,因此您不必使用 JSON.parse

如果您仍然看到相同的错误消息,则表示返回的响应存在问题。在这种情况下,请发布body 或回复,以便我们提供帮助。

根据您的修改

您从 Cloudflare 收到错误页面,这显然不是有效的 JSON。所以你的问题不是 JSON 解析,而是你请求的 URL 不正确,或者你被速率限制/阻止。

【讨论】:

  • 我现在收到错误 let username = body.data.username; ^ 类型错误:无法读取未定义的属性“用户名”
  • 我相信我找到了错误的根源。当我刚刚通过回调传递响应的主体并记录它时,我得到了 json,但是我得到了一个 524 超时错误,它被记录为 html。响应太长,无法复制和粘贴。我将发布 HTML 响应的屏幕截图。你知道是什么导致我的代码出现这个 524 超时错误吗?
  • @nhaniph Cannot read property 'username' of undefined 表示您正在解析的 JSON 不是您所期望的。没有body.data,因此也没有body.data.username
猜你喜欢
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2020-02-05
  • 2021-09-12
  • 2018-10-17
相关资源
最近更新 更多