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


当前回答

我遇到了这个错误“SyntaxError:在JSON位置中意外的令牌m”,其中令牌“m”可以是任何其他字符。

事实证明,当我使用RESTconsole进行DB测试时,我在JSON对象中漏掉了一个双引号,如{"name: "math"}。正确的应该是{"name": "math"}。

我费了很大劲才弄清楚这个笨拙的错误。恐怕其他人也会遇到类似的问题。

其他回答

对于一些人来说,这可能会对你们有所帮助: 我使用Wordpress REST API也有类似的经历。我甚至使用Postman来检查我是否有正确的路线或终点站。我后来发现我不小心在我的脚本中放了一个“echo”- hooks:

调试和检查控制台

错误原因

所以基本上,这意味着我打印了一个不是JSON的值,它与导致AJAX错误的脚本混合在一起-“SyntaxError:意外令牌r在JSON中的位置0”

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

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

与create-react-app一样,webpack-dev-server用于处理请求,并为每个请求提供index.html。所以你得到

SyntaxError:在JSON中,位置0处出现了意外的标记<。

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

您可以从这里开始按步骤操作。

在我的例子中,当在测试API节点中发送数据时,JSON对象在结尾有一个额外的逗号:

文章http://localhost: 9000 / api /文章/ 内容类型:application / json { “标题”:“sokka”, "description": "希望这有用", "username": "sokka blog4", }

所以我只需要删除额外的逗号,并发送这样的数据:

文章http://localhost: 9000 / api /文章/ 内容类型:application / json { “标题”:“sokka”, "description": "希望这有用", "用户名":"sokka blog4" }

我使用RESTclient扩展来测试我的API。

如果你试着在控制台中运行这行代码:

JSON.parse(undefined);

你会得到同样的错误信息:

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

因此,你的应用程序试图解析一个无效的未定义JSON。