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

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0

我遇到了一个类似的错误,原来是在渲染函数中的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)
    });
  },

使用line console.error(this.props. error)url,状态,err.toString()下划线。

因为这个错误看起来似乎与从服务器提取JSON数据有关,所以我尝试从一个空白db开始,但错误仍然存在。这个错误似乎在一个无限循环中被调用,可能是因为React不断尝试连接到服务器,最终导致浏览器崩溃。

编辑:

我已经用Chrome开发工具和Chrome REST客户端检查了服务器响应,数据似乎是正确的JSON。

编辑2:

虽然预期的API端点确实返回了正确的JSON数据和格式,但React轮询的是http://localhost:3000/?_=1463499798727而不是预期的http://localhost:3001/api/threads。

我在端口3000上运行webpack热重载服务器,在端口3001上运行express应用程序以返回后端数据。令人沮丧的是,这是正确的工作,我最后一次工作,找不到什么我可以改变,打破它。


当前回答

如果你在Chrome扩展中收到这个错误,很难追踪,特别是当它发生在你安装扩展的时候。然而,我找到了一个更简单的方法。

我有一个Chrome扩展,在安装插件时,从我的web服务器调用一些脚本,拉下一些默认设置。我收到了错误:

SyntaxError: Unexpected token < in JSON at position 0 in _generated_background_page.html

当你得到这个,进入扩展,找到你的扩展,点击“背景页面”超链接,检查器将打开它。然后进入网络,按CTRL+R。现在,你会看到背景页面需要加载的所有东西。

单击每一个,特别是那些连接回远程服务器的。你会在Network选项卡中看到Headers,然后是Preview。查看每个项目的预览。如果您看到该数据的报头与预期的不同,或者看到错误,那么这可能是您的原因。

在我的例子中,我的服务器脚本正在调用另一个脚本,该脚本由于运行时缺少变量而有一个错误,这使得我的application/json头与它正在发送的数据不匹配,导致意外的令牌错误。

其他回答

您正在从服务器接收HTML(或XML),但是dataType: json告诉jQuery解析为json。检查Chrome开发工具中的“网络”选项卡,查看服务器响应的内容。

对我来说,当我作为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;
    }
}

错误消息的措辞对应于你从谷歌Chrome当你运行JSON.parse('<…')。我知道你说服务器正在设置Content-Type:application/json,但我被引导相信响应体实际上是HTML。

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0" 使用line console.error(this.props. error)url, status, err.toString())下划线。

err实际上是在jQuery中抛出的,并作为变量err传递给您。这一行下划线的原因只是因为这是您记录它的地方。

我建议您添加到日志记录中。查看实际的xhr (XMLHttpRequest)属性以了解有关响应的更多信息。尝试添加console.warn(xhr.responseText),您将很可能看到正在接收的HTML。

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

在我的情况下,有问题的“持有人”在头部理想情况下,它应该是“持有人”(结束字符后的空格),但在我的情况下,它是“持有人”,字符后没有空格。希望它能帮助到一些人!