Javascript “语法错误:位置 0 处的 JSON 中出现意外标记 <”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37280274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:09:15  来源:igfitidea点击:

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

javascriptjqueryjsonreactjs

提问by Cameron Sima

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

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

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

Feed.js:94 未定义的“解析器错误”“语法错误:意外的令牌 < JSON 中的位置 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.

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

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

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

Feed.js:

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:

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

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

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

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.

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

EDIT:

编辑:

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

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

EDIT 2:

编辑2:

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

看起来虽然预期的 API 端点确实返回了正确的 JSON 数据和格式,但 React 正在轮询http://localhost:3000/?_=1463499798727而不是预期的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.

我正在端口 3000 上运行 webpack 热重载服务器,其中 express 应用程序在端口 3001 上运行以返回后端数据。令人沮丧的是,这在我上次处理它时运行正常,并且找不到我可能会更改以破坏它的内容。

采纳答案by Bryan Field

The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...'). I know you said the server is setting Content-Type:application/json, but I am led to believe the response bodyis actually HTML.

错误消息的措辞与您在运行JSON.parse('<...'). 我知道你说服务器正在设置Content-Type:application/json,但我相信响应正文实际上是 HTML。

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

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

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

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

The errwas actually thrown within jQuery, and passed to you as a variable err. The reason that line is underlined is simply because that is where you are logging it.

err内部实际上抛出jQuery,并传递给你作为一个变量err。该行带有下划线的原因仅仅是因为这是您记录它的地方。

I would suggest that you add to your logging. Looking at the actual xhr(XMLHttpRequest) properties to learn more about the response. Try adding console.warn(xhr.responseText)and you will most likely see the HTML that is being received.

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

回答by nil

You're receiving HTML (or XML) back from the server, but the dataType: jsonis telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.

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

回答by Andrew Shenstone

This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in. the redirected url responds to html, not json. The first character in a html response is <.

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

回答by VictorL

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

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

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"}

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

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

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

回答by Kev

In my case, I was getting this running webpack, and it turned out to be some corruption somewhere in the local node_modules dir.

就我而言,我正在运行这个 webpack,结果是本地 node_modules 目录中的某个地方出现了一些损坏。

rm -rf node_modules
npm install

...was enough to get it working right again.

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

回答by Colin

I my case the error was a result of me not assigning my return value to a variable. The following caused the error message:

我的情况是错误是因为我没有将返回值分配给变量。以下导致错误消息:

return new JavaScriptSerializer().Serialize("hello");

I changed it to:

我把它改成:

string H = "hello";
return new JavaScriptSerializer().Serialize(H);

Without the variable JSON is unable to properly format the data.

没有变量 JSON 无法正确格式化数据。

回答by sriram veeraghanta

This error occurs when you define the response as application/jsonand you are getting a HTML as a response. Basically, this happened when you are writing server side script for specific url with a response of JSON but the error format is in HTML.

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

回答by Tomas Grecio Ramirez

Make sure that response is in JSON format otherwise fires this error.

确保响应采用 JSON 格式,否则会触发此错误。

回答by MPV

This might be old. But, it just occurred in angular, the content type for request and response were different in my code. So, check headers for ,

这可能是旧的。但是,它只是发生在 angular 中,请求和响应的内容类型在我的代码中是不同的。所以,检查标题,

 let headers = new Headers({
        'Content-Type': 'application/json',
        **Accept**: 'application/json'
    });

in React axios

在反应 axios 中

axios({
  method:'get',
  url:'http://  ',
 headers: {
         'Content-Type': 'application/json',
        Accept: 'application/json'
    },
  responseType:'json'
})

jQuery Ajax:

jQuery Ajax:

 $.ajax({
      url: this.props.url,
      dataType: 'json',
**headers: { 
          'Content-Type': 'application/json',
        Accept: 'application/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)
    });
  },

回答by Dave Skender

In my case, for an Azure hosted Angular 2/4 site, my API call to mySite/api/... was redirecting due to mySite routing issues. So, it was returning the HTML from the redirected page instead of the api JSON. I added an exclusion in a web.config file for the api path.

就我而言,对于 Azure 托管的 Angular 2/4 站点,由于 mySite 路由问题,我对 mySite/api/... 的 API 调用正在重定向。因此,它从重定向页面返回 HTML,而不是 api JSON。我在 web.config 文件中为 api 路径添加了一个排除项。

I was not getting this error when developing locally because the Site and API were on different ports. There is probably a better way to do this ... but it worked.

我在本地开发时没有收到此错误,因为站点和 API 位于不同的端口上。可能有更好的方法来做到这一点……但它奏效了。

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <system.webServer>
        <rewrite>
        <rules>
        <clear />

        <!-- ignore static files -->
        <rule name="AngularJS Conditions" stopProcessing="true">
        <match url="(app/.*|css/.*|fonts/.*|assets/.*|images/.*|js/.*|api/.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="None" />
        </rule>

        <!--remaining all other url's point to index.html file -->
        <rule name="AngularJS Wildcard" enabled="true">
        <match url="(.*)" />
        <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
        <action type="Rewrite" url="index.html" />
        </rule>

        </rules>
        </rewrite>
    </system.webServer>
</configuration>