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


当前回答

我的问题是,我得到的数据在一个字符串不是在一个适当的JSON格式,然后我试图解析它。简单的例子:JSON。parse('{hello there}')将在h处给出错误。在我的例子中,回调url在对象之前返回了一个不必要的字符:employee_names([{"name":....在e(0)处有误差。我的回调URL本身有一个问题,当修复时,只返回对象。

其他回答

在我的例子中,对于一个Azure托管的Angular 2/4站点,我对mySite/ API /…由于mySite路由问题正在重定向。因此,它从重定向页面返回HTML,而不是api JSON。我在网上添加了一个排除项。API路径的配置文件。

我在本地开发时没有得到这个错误,因为站点和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>

2022年更新:这篇文章是几年前写的。我认为这个建议更像是一个变通方案——直接解决方案。更好的托管模式是不要试图在你的网站路径下托管这些api路径;相反,将它们完全托管在独立的基本url上。对于我的用例示例,API和Web路径将是完全独立的Azure Web服务,并将获得不同的URL端点。

检查发出请求的端点地址。 如果它拼写错误,这可能是错误的原因,因为结束点返回HTML

我得到了同样的错误,而调用一个API在React中使用获取API与POST方法。

之前:

fetch('/api/v1/tour',{
      method:"POST",
      headers:{"Content-type":"json/application"},
      body:JSON.stringify(info)
    })
    .then((response)=>response.json())
    .then((json)=>{
      if(json.status === 'success')
        alert(json.message)
      else
        console.log('something went wrong :(')
    }).catch(e=>console.log(e))

我通过将头文件更改为{"Content-type":"application/json"}来解决这个错误:

后:

fetch('/api/v1/tour',{
      method:"POST",
      headers:{"Content-type":"application/json"},
      body:JSON.stringify(info)
    })
    .then((response)=>response.json())
    .then((json)=>{
      if(json.status === 'success')
        alert(json.message)
      else
        console.log('something went wrong :(')
    }).catch(e=>console.log(e))

在我的情况下,我得到这个运行的webpack。它在本地node_modules目录的某个地方被损坏了。

rm -rf node_modules
npm install

...足够让它恢复正常工作了。

正如其他答案所描述的那样,畸形的JSON或HTML而不是JSON是这个问题的根本原因,然而在我的情况下,我不能可靠地复制这个错误,就好像服务器有时返回有效的JSON,而其他时候返回其他像HTML错误页面或类似的东西。

为了避免它完全破坏页面,我手动尝试解析返回的内容,并分享它,以防它帮助其他人解决问题。

const url = "https://my.server.com/getData";

fetch(url).then(response => {
  if (!response.ok) return; // call failed

  response.text().then(shouldBeJson => { // get the text-only of the response
    let json = null;
    try {
      json = JSON.parse(shouldBeJson); // try to parse that text
    } catch (e) {
      console.warn(e); // json parsing failed
      return;
    };
    if (!json) return; // extra check just to make sure we have something now.

    // do something with my json object
  });
});

虽然这显然不能解决问题的根本原因,但它仍然可以帮助更优雅地处理问题,并在失败时采取某种合理的操作。