简体   繁体   English

意外令牌 < 在 JSON 中 position 0

[英]Unexpected token < in JSON at position 0

If I do curl, the server returns an array of posts objects, like this:如果我执行 curl,服务器会返回一个帖子对象数组,如下所示:

curl http://localhost/api/posts/
[
    {
        "id": 7,
        "target": {
            "body": "This is the body",
            "title": "Airbnb raising a reported $850M at a $30B valuation",
            "user": {
                "first_name": "ben",
                "last_name": "jamin"
            }
        }
    },
    {
        "id": 11,
        "target": {
            "body": "This is the body",
            "title": "Browsing the APISSS",
            "user": {
                "first_name": "user",
                "last_name": "two"
            }
        }
    }
]

I tried getting this using the fetch api:我尝试使用 fetch api 得到这个:

fromServer() {
    console.log('fromServer')
    var headers = new Headers();
    headers.append('Accept', 'application/json');
    let a = fetch('http://test.com/api/posts/', headers)
        .then(function(response) {
                if (response.status !== 200) {
                    console.log('There was a problem. Status Code: ' +  response.status);  
                    return;
                }

                response.json().then(function(data) {  
                    console.log(data);
                });  
            }  
        )  
        .catch(function(err) {  
            console.log('Fetch Error :-S', err);  
        });
}

But I am getting this error:但我收到此错误:

Unexpected token < in JSON at position 0意外令牌 < 在 JSON 中 position 0

SyntaxError: Unexpected token < in JSON at position 0 SyntaxError: Unexpected token < in JSON at position 0

How can I solve this problem?我怎么解决这个问题? Could you please help me.请你帮助我好吗。 Thank you.谢谢你。

It is clear that you have some syntax error while parsing response into json object. 很明显,在将响应解析为json对象时,您会遇到一些语法错误。

Remove all the comments from server json file if any. 从服务器json文件中删除所有注释(如果有)。

If it is not: I believe the response body is not json. 如果不是:我相信响应主体不是json。

You're receiving HTML (or XML) back from the server, but code is enable to parse as JSON. 您正在从服务器接收回HTML(或XML),但是启用了将代码解析为JSON的功能。 Check the "Network" tab in Chrome dev tools to see contents of the server's response. 在Chrome开发者工具中检查“网络”标签,以查看服务器响应的内容。

Or debug using this code: (as "Jaromanda X" said) 或使用以下代码进行调试:(如“ Jaromanda X”所述)

.then(function(response) {
                console.log(response);
                console.log(response.status);
                console.log(response.json());
                console.log(response.text());
                })  
        .catch(function(err) {  
            console.log('Fetch Error :-S', err);  
        });

Please check that your server is giving response in JSON format only. 请检查您的服务器是否仅以JSON格式给出响应。 For Associative data you should start your JSON object with " { " not " [ " . 对于关联数据,您应该以“ {”而非“ [”开始JSON对象。 So your data should be in below format . 因此,您的数据应采用以下格式。

{ "data":[ { "id": 7, "target": { "body": "This is the body", "title": "Airbnb raising a reported $850M at a $30B valuation", "user": { "first_name": "ben", "last_name": "jamin" } } }, { "id": 11, "target": { "body": "This is the body", "title": "Browsing the APISSS", "user": { "first_name": "user", "last_name": "two" } } } ] } And you can get all data from response.data . { "data":[ { "id": 7, "target": { "body": "This is the body", "title": "Airbnb raising a reported $850M at a $30B valuation", "user": { "first_name": "ben", "last_name": "jamin" } } }, { "id": 11, "target": { "body": "This is the body", "title": "Browsing the APISSS", "user": { "first_name": "user", "last_name": "two" } } } ] }然后您可以从response.data获取所有数据。 For more detail follow this link . 有关更多详细信息,请单击此链接

The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...'). 错误消息的措词与您运行JSON.parse('<...')时从Google Chrome获得的内容相对应。 I know you said the server is setting Content-Type:application/json, but I am led to believe the response body is actually HTML. 我知道您说服务器正在设置Content-Type:application / json,但是我被认为是响应主体实际上是HTML。

"SyntaxError: Unexpected token < in JSON at position 0" “ SyntaxError:JSON中位置0处的意外令牌<”

with the line console.error(this.props.url, status, err.toString()) underlined. 在console.error(this.props.url,status,err.toString())下划线。 The err was actually thrown within jQuery, and passed to you as a variable err. 错误实际上是在jQuery中引发的,并作为变量err传递给您。 The reason that line is underlined is simply because that is where you are logging it. 带下划线的原因仅仅是因为这就是您要记录的地方。

I would suggest that you add to your logging. 我建议您将其添加到日志记录中。 Looking at the actual xhr (XMLHttpRequest) properties to learn more about the response. 查看实际的xhr(XMLHttpRequest)属性以了解有关响应的更多信息。 Try adding console.warn(xhr.responseText) and you will most likely see the HTML that is being received. 尝试添加console.warn(xhr.responseText),您很可能会看到正在接收的HTML。

Please correct your code according to above explanation. 请根据以上说明更正您的代码。

so, you can use with start JSON array ; 因此,您可以将其与start JSON array一起使用;

{

"array": [

    {
        "id": 7,
        "target": {
            "body": "This is the body",
            "title": "Airbnb raising a reported $850M at a $30B valuation",
            "user": {
                "first_name": "ben",
                "last_name": "jamin"
            }
        }
    },
    {
        "id": 11,
        "target": {
            "body": "This is the body",
            "title": "Browsing the APISSS",
            "user": {
                "first_name": "user",
                "last_name": "two"
            }
        }
    }
]

}

So the problem was this: Since I was testing it from the vagrant machine in LAN and in my hosts file I added the ip of vagrant machine as the url (test.com), the device was not able to fetch to that url. 所以问题是这样的:由于我是从LAN上的无业游民机器中测试它的,而在我的主机文件中,我添加了无业游民机器的IP作为URL(test.com),因此该设备无法获取该URL。 After I changed the vagrant machine to port forward and gave the original IP address of the machine, I was able to fetch the json objects. 在将无所事事的机器更改为端口转发并提供了机器的原始IP地址之后,我能够获取json对象。 Thank you all for your help. 谢谢大家的帮助。

您可以尝试添加dataType属性,就像dataType: 'html'dataType: 'text'

Well for me it was because the port was already in use, you can try killing the port by running the below command in cmd(admin mode)对我来说这是因为端口已经在使用中,您可以尝试通过在 cmd(管理员模式)下运行以下命令来终止端口

taskkill /F /IM node.exe taskkill /F /IM node.exe

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM