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

新手上路,请多包涵

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

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)
    });
  },

带有下划线的 console.error(this.props.url, status, err.toString() 行。

由于看起来该错误似乎与从服务器提取 JSON 数据有关,因此我尝试从空白数据库开始,但错误仍然存在。该错误似乎是在无限循环中调用的,大概是因为 React 不断尝试连接到服务器并最终使浏览器崩溃。

编辑:

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

编辑2:

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

我正在端口 3000 上运行 webpack 热重载服务器,并在端口 3001 上运行 express 应用程序以返回后端数据。令人沮丧的是,我上次处理它时它工作正常,但找不到我可能改变的东西来破坏它。

原文由 Cameron Sima 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

错误消息的措辞与您在运行 JSON.parse('<...') 时从 Google Chrome 获得的内容相对应。我知道您说服务器正在设置 Content-Type:application/json ,但我被引导相信响应 正文 实际上是 HTML。

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

带有下划线的 console.error(this.props.url, status, err.toString()) 行。

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

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

原文由 700 Software 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

原文由 nil 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题