“ SyntaxError:JSON中位置0处的意外令牌<”

JavaScript

Stafan小哥

2020-03-11

在处理类似于Facebook的内容提要的React应用程序组件中,我遇到了一个错误:

Feed.js:94未定义“ parsererror”“ SyntaxError:JSON中位置0处的意外令牌<

我遇到了类似的错误,事实证明这是render函数中HTML的错字,但这里似乎并非如此。

更令人困惑的是,我将代码回滚到了较早的已知工作版本,但仍然遇到错误。

Feed.js:

import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '', 
            text: '', 
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author, 
                                text: text, 
                                included: included,
                                victim: victim
                              })
    this.setState({author: '', 
                  text: '', 
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (
    <div className="threadsBox">
      <h1>Feed</h1>
      <div>
        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />
      </div>
    </div>
    )
  }
})

module.exports = ThreadsBox

在Chrome开发人员工具中,错误似乎是由以下功能引起的:

 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

console.error(this.props.url, status, err.toString()下划线标出。

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.

第605篇《“ SyntaxError:JSON中位置0处的意外令牌<”》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

17个回答
神乐十三 2020.03.11

JSON中的意外令牌<位于位置0

解决此错误的简单方法是在styles.less文件中写入注释

Harry逆天Eva 2020.03.11

就我而言(后端),我正在使用res.send(token);

当我更改为res.send(data)时,一切都固定了;

如果一切正常,并按预期进行发布,则可能需要检查一下,但是错误始终在您的前端弹出。

Pro逆天猿 2020.03.11

那些正在使用create-react-app并尝试获取本地json文件的人。

与中的一样create-react-appwebpack-dev-server用于处理请求,并为每个请求提供服务index.html所以你越来越

SyntaxError:JSON中位置0处的意外令牌<。

要解决此问题,您需要弹出应用程序并修改webpack-dev-server配置文件。

您可以从这里开始

理查德Green 2020.03.11

这可能是由于您的JavaScript代码正在查看某些json响应而导致您收到了其他类似文本的信息。

猪猪阿飞 2020.03.11

此错误的可能性是巨大的。

就我而言,我发现该问题是由于添加homepage文件package.json引起的。

值得检查:package.json更改中:

homepage: "www.example.com"

hompage: ""   
TonySamGreen 2020.03.11

对于某些人来说,这可能对您有所帮助:我在Wordpress REST API方面也有类似的经验。我什至用邮差来检查我是否有正确的路由或端点。后来我发现我不小心在脚本中放了一个“ echo”-钩子:

调试并检查您的控制台

错误原因

因此,基本上,这意味着我打印的值不是与导致AJAX错误的脚本混合的JSON-“ SyntaxError:JSON位置0处的意外令牌r”

宝儿Pro 2020.03.11

在python中,您可以在将结果发送到html模板之前使用json.Dump(str)。使用此命令字符串转换为正确的json格式并发送到html模板。将结果发送到JSON.parse(result)之后,这是正确的响应,您可以使用它。

神无Davaid 2020.03.11

对我来说,当我作为JSON返回的对象的属性之一引发异常时,就会发生这种情况。

public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        //throws when Clients is null
        foreach (var c in Clients) {
            count += c.Value;
        }
        return count;
    }
}

添加一个空检查,为我修复了它:

public Dictionary<string, int> Clients { get; set; }
public int CRCount
{
    get
    {
        var count = 0;
        if (Clients != null) {
            foreach (var c in Clients) {
                count += c.Value;
            }
        }
        return count;
    }
}
神奇Davaid 2020.03.11

只是基本检查,请确保您在json文件中没有任何注释

//comments here will not be parsed and throw error
TonyPro 2020.03.11

花了很多时间后,我发现我的问题是在package.json文件上定义了“主页”,这导致我的应用无法在Firebase上运行(相同的“令牌”错误)。我使用create-react-app创建了我的react应用,然后使用READ.me文件上的firebase指南部署到github页面,意识到我必须做额外的工作才能使路由器正常工作,然后切换到firebase。github指南已在package.json上添加了主页密钥,并导致了部署问题。

GOL蛋蛋 2020.03.11

确保响应为JSON格式,否则会引发此错误。

蛋蛋伽罗猿 2020.03.11

当您将响应定义为application/json并且正在获取HTML作为响应时,会发生此错误基本上,当您使用JSON响应为特定URL编写服务器端脚本但错误格式为HTML时,就会发生这种情况。

满天星 2020.03.11

我遇到了此错误“ SyntaxError:JSON中的位置处出现意外的标记m”,其中标记“ m”可以是任何其他字符。

原来,当我使用RESTconsole进行数据库测试时,我错过了JSON对象中的双引号之一,例如{“ name:” math“},正确的应该是{” name“:” math“}

我花了很多精力来找出这个笨拙的错误。恐怕其他人会遇到类似的麻烦。

SamItachi阿飞 2020.03.11

以我为例,我正在运行此Webpack,结果证明是本地node_modules目录中某处的损坏。

rm -rf node_modules
npm install

...足以使其再次正常工作。

蛋蛋神乐 2020.03.11

这最终成为我的权限问题。我试图通过Cancan访问未经授权的网址,因此该网址已切换为users/sign_in重定向的网址会响应html,而不是json。html响应中的第一个字符是<

Tony达蒙Mandy 2020.03.11

您正在从服务器返回HTML(或XML),但是dataType: json告诉jQuery解析为JSON。在Chrome开发者工具中检查“网络”标签,以查看服务器响应的内容。

Near神乐路易 2020.03.11

就我而言,该错误是由于我未将返回值分配给变量而导致的。导致错误消息的原因如下:

return new JavaScriptSerializer().Serialize("hello");

我将其更改为:

string H = "hello";
return new JavaScriptSerializer().Serialize(H);

没有变量,JSON无法正确格式化数据。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android