简体   繁体   English

具有JSON.parse的JSON中位置0处的意外令牌<

[英]Unexpected token < in JSON at position 0 with JSON.parse

I am iterating through an object and making several requests with items in that object to an API, for fetching data & then sending it to a database. 我正在遍历一个对象,并对该对象的项目向API发出了几个请求,以获取数据并将其发送到数据库。 When receiving the data, I am using JSON.parse() to store the json in a variable and sending it to a callback where it is handled and will eventually be sent to a database. 接收数据时,我正在使用JSON.parse()将json存储在变量中,然后将其发送到回调中,在该回调中进行处理并将最终将其发送到数据库。

After researching this issue and seeing similar questions here on StackOverflow, I still cannot figure out my issue considering the data from the request is getting parsed fine, but I get the issue a couple minutes after I run my code. 在研究了这个问题并在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);
    });





After I console.log all the data I get (which is being somewhat parsed correctly considering its being logged), the console gives me the Unexpected token < in JSON at position 0 error a couple minutes after I have ran my code. 在我console.log获得的所有数据后(考虑到已记录的数据,它已经被正确解析),控制台在运行代码后几分钟,在JSON位置0向我提供了Unexpected令牌<错误。 When I console.log(player), there are no issues and there is an object that is logged for each player. 当我console.log(player)时,没有问题,并且为每个玩家记录了一个对象。

NOTE: I have created another account for this API so that others can test this issue with a authorization id that is not my actual authorization id. 注意:我已经为此API创建了另一个帐户,以便其他人可以使用不是我的实际授权ID的授权ID测试此问题。

Error from passing body through callback function and logging it. 通过回调函数传递主体并将其记录下来时出错。

<!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>

In your request options, rather than setting the header, you could do: 在您的请求选项中,您可以执行以下操作,而不是设置标题:

// 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);
    });
}

That will automatically convert the response to a JSON object, so you won't have to use JSON.parse . 它将自动将响应转换为JSON对象,因此您不必使用JSON.parse

If you still see the same error message, then that would mean there's some problem with the response being returned. 如果仍然看到相同的错误消息,则意味着返回响应存在一些问题。 In that case, post the body or response so we can help. 在这种情况下,请张贴body或回应,以便我们提供帮助。

Based on your edit : 根据您的编辑

You're getting an error page from Cloudflare, which is obviously not valid JSON. 您从Cloudflare收到了一个错误页面,该页面显然不是有效的JSON。 So your problem is not JSON parsing, it's the URL you are requesting is incorrect, or you're being rate-limited/blocked. 因此,您的问题不是JSON解析,而是您请求的URL不正确,或者您受到速率限制/阻止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JSON 中的意外令牌 a 在 position 0 在 JSON.parse - unexpected token a in JSON at position 0 at JSON.parse JSON. 解析 position 0 处的意外令牌 - JSON.parse unexpected token s at position 0 未捕获到的SyntaxError:JSON中的意外令牌u在JSON.parse的位置0 - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse JSON.parse 位置 0 处的 JSON 中的意外标记 u - Unexpected token u in JSON at position 0 at JSON.parse 意外的标记 ? 使用JSON.parse在位置x的JSON中 - Unexpected token ? in JSON at position x using JSON.parse 未捕获的SyntaxError:JSON.parse中位置0的JSON中的意外标记a( <anonymous> ) - Uncaught SyntaxError: Unexpected token a in JSON at position 0 at JSON.parse (<anonymous>) JSON.parse() 导致错误:`SyntaxError: Unexpected token in JSON at position 0` - JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0` JSON.parse(): SyntaxError: Unexpected token in JSON at position 0 - JSON.parse(): SyntaxError: Unexpected token � in JSON at position 0 JSON.parse() 错误 SyntaxError: Unexpected token &lt; in JSON at position 0 - JSON.parse() Error SyntaxError: Unexpected token < in JSON at position 0 语法错误:JSON 中的意外令牌 e 在 position 1 与 JSON.parse() - SyntaxError: Unexpected token e in JSON at position 1 with JSON.parse()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM