"SyntaxError: Unexpected token <JSON 中的位置 0" [英] "SyntaxError: Unexpected token < in JSON at position 0"

查看:24
本文介绍了"SyntaxError: Unexpected token <JSON 中的位置 0"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

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

我遇到了类似的错误,结果证明是渲染函数中 HTML 中的拼写错误,但这里似乎并非如此.

更令人困惑的是,我将代码回滚到较早的已知工作版本,但仍然出现错误.

Feed.js:

从'react'导入React;var ThreadForm = React.createClass({getInitialState: 函数 () {返回{作者:'',文本: '',包括: '',受害者: ''}},handleAuthorChange:函数(e){this.setState({作者: e.target.value})},handleTextChange:函数(e){this.setState({text: e.target.value})},handleIncludedChange:函数(e){this.setState({包括:e.target.value})},handleVictimChange:函数(e){this.setState({受害者: e.target.value})},句柄提交:函数(e){e.preventDefault()var author = this.state.author.trim()var text = this.state.text.trim()var 包含 = this.state.included.trim()var 受害者 = this.state.victim.trim()if (!text || !author || !included || !victim) {返回}this.props.onThreadSubmit({作者:作者,文字:文字,包括:包括,受害者:受害者})this.setState({作者: '',文本: '',包括: '',受害者: ''})},渲染:函数(){返回 (<form className="threadForm" onSubmit={this.handleSubmit}><输入类型=文本"占位符="你的名字"值={this.state.author}onChange={this.handleAuthorChange}/><输入类型=文本"placeholder="说点什么..."值={this.state.text}onChange={this.handleTextChange}/><输入类型=文本"placeholder="命名你的受害者"值={this.state.victim}onChange={this.handleVictimChange}/><输入类型=文本"占位符=谁能看到?"值={this.state.included}onChange={this.handleIncludedChange}/><input type="submit" value="post"/></表单>)}})var ThreadsBox = React.createClass({loadThreadsFromServer: 函数 () {$.ajax({网址:this.props.url,数据类型:'json',缓存:假,成功:功能(数据){this.setState({数据: 数据})}.bind(this),错误:函数(xhr,状态,错误){console.error(this.props.url, status, err.toString())}.绑定(这个)})},handleThreadSubmit:函数(线程){var 线程 = this.state.datavar newThreads =threads.concat([thread])this.setState({data: newThreads})$.ajax({网址:this.props.url,数据类型:'json',类型:'POST',数据:线程,成功:功能(数据){this.setState({数据: 数据})}.bind(this),错误:函数(xhr,状态,错误){this.setState({数据:线程})console.error(this.props.url, status, err.toString())}.绑定(这个)})},getInitialState: 函数 () {返回{数据:[]}},componentDidMount: 函数 () {this.loadThreadsFromServer()setInterval(this.loadThreadsFromServer, this.props.pollInterval)},渲染:函数(){返回 (<div className="threadsBox"><h1>进料</h1><div><ThreadForm onThreadSubmit={this.handleThreadSubmit}/>

)}})module.exports = ThreadsBox

在 Chrome 开发者工具中,错误似乎来自这个函数:

 loadThreadsFromServer: 函数 loadThreadsFromServer() {$.ajax({网址:this.props.url,数据类型:'json',缓存:假,成功:功能(数据){this.setState({数据:数据});}.bind(this),错误:函数(xhr,状态,错误){console.error(this.props.url, status, err.toString());}.绑定(这个)});},

带有下划线的 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 热重载服务器,express 应用程序在端口 3001 上运行以返回后端数据.令人沮丧的是,这在我上次工作时正常工作,但找不到我可能会更改以破坏它的内容.

解决方案

我遇到了这个错误SyntaxError: Unexpected token m in JSON at position",其中标记 'm' 可以是任何其他字符.

结果是我在使用 RESTconsole 进行数据库测试时遗漏了 JSON 对象中的一个双引号,如 {"name: "math"},正确的应该是 {"name": "math"}

我花了很多精力才弄清楚这个笨拙的错误.我担心其他人会遇到类似的无赖.

In a React app component which handles Facebook-like content feeds, I am running into an error:

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

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.

More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.

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

In Chrome developer tools, the error seems to be coming from this function:

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

with the line console.error(this.props.url, status, err.toString() underlined.

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.

解决方案

I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.

It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}

It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.

这篇关于&quot;SyntaxError: Unexpected token &lt;JSON 中的位置 0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆