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

Cam*_*ima 166 javascript jquery json reactjs

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

Feed.js:94 undefined"parsererror""SyntaxError:位于0的JSON中的意外标记<

我遇到了一个类似的错误,结果是渲染函数中的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
Run Code Online (Sandbox Code Playgroud)

在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)
    });
  },
Run Code Online (Sandbox Code Playgroud)

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应用程序以返回后端数据.令人沮丧的是,这是我上一次工作时正常工作,无法找到我可以改变的东西来打破它.

Bry*_*eld 136

错误消息的措辞与您在运行时从Google Chrome中获得的内容相对应JSON.parse('<...').我知道你说服务器正在设置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.

  • 感谢额外的调试声明,虽然我需要使用`console.warn(jqxhr.responseText)`.这对诊断我的问题非常有帮助. (7认同)
  • 谢谢,我做了这个,你是对的 - 反应是轮询错误的网址,并返回index.html的内容.我只是找不出原因. (3认同)
  • 您还可以进入开发人员设置 -&gt; 网络选项卡来查看您实际收到的响应。当您在同一服务器(例如本地主机)上运行后端和前端时,会发生这种情况。要解决这个问题,请在 `React` 根项目文件夹内的 `package.json` 中添加以下行: `"proxy": "http://localhost:5000" `,(或者您的端口而不是 `5000`希望回复您的请求)。 (3认同)
  • 就我而言,发生了 PHP 错误,导致服务器返回 HTML 而不是有效的 JSON。 (2认同)

nil*_*nil 38

您正在从服务器接收HTML(或XML),但dataType: json它告诉jQuery要解析为JSON.查看Chrome开发工具中的"网络"标签,查看服务器响应的内容.


Sup*_*ade 23

SyntaxError:JSON 中位置 0 处出现意外标记 <


您将获得 HTML 文件(或 XML)而不是 json。

Html 文件以<!DOCTYPE html>.

https://我通过忘记我的方法中的“实现”此错误fetch

fetch(`/api.github.com/users/${login}`)
    .then(response => response.json())
    .then(setData);
Run Code Online (Sandbox Code Playgroud)

我验证了我的预感:

我将响应记录为文本而不是 JSON。

fetch(`/api.github.com/users/${login}`)
    .then(response => response.text())
    .then(text => console.log(text))
    .then(setData);
Run Code Online (Sandbox Code Playgroud)

是的,一个 html 文件。

解决方案:

https://我通过在我的方法中添加回 来修复错误fetch

fetch(`https://api.github.com/users/${login}`)
    .then(response => response.json())
    .then(setData)
    .catch(error => (console.log(error)));
Run Code Online (Sandbox Code Playgroud)


Asi*_*K T 10

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

var string = "some string";
JSON.parse(string)
Run Code Online (Sandbox Code Playgroud)

会抛出一个错误,说

未捕获的语法错误:JSON 中位置 0 处出现意外标记

因为,其中的第一个字符strings& 它现在不是有效的 JSON。这也可能会在两者之间引发错误。喜欢:

var invalidJSON= '{"foo" : "bar", "missedquotehere : "value" }';
JSON.parse(invalidJSON)
Run Code Online (Sandbox Code Playgroud)

会抛出错误:

VM598:1 Uncaught SyntaxError: Unexpected token v in JSON at position 36
Run Code Online (Sandbox Code Playgroud)

invalidJSON因为我们故意错过了 JSON 字符串中位置 36 处的引号。

如果你解决这个问题:

var validJSON= '{"foo" : "bar", "missedquotehere" : "value" }';
JSON.parse(validJSON)
Run Code Online (Sandbox Code Playgroud)

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

此错误可以在任何地方和任何框架/库中引发。大多数时候,您可能正在读取不是有效 JSON 的网络响应。所以调试这个问题的步骤可以是这样的:

  1. curl或者点击您正在调用的实际 API。
  2. 记录/复制响应并尝试使用JSON.parse. 如果您遇到错误,请修复它。
  3. 如果不是,请确保您的代码没有改变/更改原始响应。


小智 9

这最终成为我的权限问题.我试图访问一个我没有使用cancan授权的网址,所以网址被切换到了users/sign_in.重定向的url响应html,而不是json.html响应中的第一个字符是<.


小智 8

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


小智 7

我遇到了这个错误"SyntaxError:位于JSON中的意外令牌m",其中令牌"m"可以是任何其他字符.

事实证明,当我使用RESTconsole进行数据库测试时,我错过了JSON对象中的一个双引号,{{name:"math"},正确的应该是{"name":"math"}

我花了很多心思才弄清楚这个笨拙的错误.我担心其他人会遇到类似的失败者.


an0*_*0us 7

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

如 中所示create-react-appwebpack-dev-server用于处理请求,并为每个请求提供服务index.html。所以你得到了

语法错误:JSON 中位置 0 处出现意外标记 <。

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

您可以按照此处的步骤进行操作。


Abh*_*D K 6

我遇到了同样的问题,
我从 $.ajax 方法中删除了dataType:'json'


Kev*_*Kev 5

在我的情况下,我正在运行这个运行webpack,结果在本地node_modules目录中的某处出现了一些损坏.

rm -rf node_modules
npm install
Run Code Online (Sandbox Code Playgroud)

......足以让它再次正常工作.

  • 除此之外,我尝试删除 package-lock.json。然后它对我有用。 (2认同)

css*_*hus 5

对于未来的谷歌用户:

\n

如果服务器端功能崩溃,将会生成此消息。

\n

或者如果服务器端函数根本不存在(即函数名称中的拼写错误)

\n

所以 - 假设您正在使用 GET 请求...一切看起来都很完美并且您已经对所有内容进行了三次检查...

\n

再次检查 GET 字符串。我的是:

\n
\'/theRouteIWant&someVar=Some value to send\'\n
Run Code Online (Sandbox Code Playgroud)\n

应该

\n
\'/theRouteIWant?someVar=Some value to send\'\n               ^\n
Run Code Online (Sandbox Code Playgroud)\n

碰撞 ! \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0(...... 服务器上不可见......)

\n

Node/Express 发回令人难以置信的(无)有用的消息:
\n Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

\n

根据Eliezer Berlin的评论,令牌通常是服务器返回的<一段意外的 HTML,例如 in 。<head>

\n