在一个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应用程序以返回后端数据。令人沮丧的是,这是正确的工作,我最后一次工作,找不到什么我可以改变,打破它。


当前回答

检查发出请求的端点地址。 如果它拼写错误,这可能是错误的原因,因为结束点返回HTML

其他回答

简而言之,如果您得到这个错误或类似的错误,这只意味着一件事:在我们的代码库中,我们期望处理有效的JSON格式,但我们没有得到。例如,

var string = "some string";
JSON.parse(string)

会抛出一个错误,说

Uncaught SyntaxError: JSON中0号位置出现了意外的令牌

因为,字符串中的第一个字符是s &它现在不是一个有效的JSON。这也会在中间产生错误。如:

var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(invalidJSON)

将抛出错误:

VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36

因为我们故意在JSON字符串invalidJSON的第36位漏掉了一个引号。

如果你解决了这个问题:

var validJSON= '{"foo" : "bar", "missedquotehere" : "value" }';
JSON.parse(validJSON)

会给你一个JSON格式的对象。

此错误可以在任何位置和任何框架/库中抛出。大多数情况下,您可能会读取一个不是有效JSON的网络响应。所以调试这个问题的步骤可以是这样的:

curl或击中你正在调用的实际API。 记录/复制响应,并尝试使用JSON.parse解析它。如果你得到错误,修复它。 如果不是,请确保您的代码没有突变/改变原始响应。

错误消息的措辞对应于你从谷歌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。

对我来说,这最终是一个权限问题。我试图访问一个我没有cancan授权的url,所以url被切换到users/sign_in。重定向url响应html,而不是json。html响应中的第一个字符是<。

Protip:在本地Node.js服务器上测试json ?确保您还没有路由到该路径的内容

'/:url(app|assets|stuff|etc)';

在花了很多时间之后,我发现在我的情况下,问题是在我的包上定义了“主页”。Json文件使我的应用程序不能在firebase上工作(相同的“令牌”错误)。 我使用create-react-app创建了我的react应用程序,然后我在READ上使用了firebase指南。me文件部署到github页面,意识到我必须做额外的工作路由器的工作,并切换到firebase。Github指南已经在包上添加了主页键。Json,并导致部署问题。