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


当前回答

为了补充答案,当API响应包含时也会发生这种情况

<?php{username: 'Some'}

当您的后端使用PHP时,可能会出现这种情况。

其他回答

在我的情况下,我得到这个运行的webpack。它在本地node_modules目录的某个地方被损坏了。

rm -rf node_modules
npm install

...足够让它恢复正常工作了。

如果其他人正在从Mozilla Web API的“using fetch”文档中使用fetch: (这个很有用:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

  fetch(api_url + '/database', {
    method: 'POST', // or 'PUT'
    headers: {
     'Content-Type': 'application/json'
    },
    body: qrdata //notice that it is not qr but qrdata
  })
  .then((response) => response.json())
  .then((data) => {
    console.log('Success:', data);
  })  
  .catch((error) => {
  console.error('Error:', error);  });

这是在函数内部:

async function postQRData(qr) {

  let qrdata = qr; //this was added to fix it!
  //then fetch was here
}

我传入我的函数qr我认为是一个对象,因为qr看起来像这样:{"name": "Jade", "lname": "Bet", "pet":"cat"},但我一直得到语法错误。 当我将它赋值给其他对象时:let qrdata = qr;它工作。

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

在大多数情况下,我得到这个错误,当API抛出一个文本格式的错误。 我的建议是查看错误文本内容,以找出发生了什么错误。

jQuery = > set dataType: 'text' fetch = > response .text()代替response .json()

我在学习教程后也遇到了同样的错误信息。我们的问题似乎是'url: this.props。Url '在ajax调用中。在反应。DOM创建元素时,我的元素是这样的。

ReactDOM.render(
    <CommentBox data="/api/comments" pollInterval={2000}/>,
    document.getElementById('content')
);

这个CommentBox在它的props中没有url,只有数据。当我切换url: this.props.url -> url: this.props。数据,它对服务器做出了正确的调用,我得到了预期的数据。

我希望这能有所帮助。