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


当前回答

对于CRA制作的React应用程序,在获取任何<dummy.json>的JSON数据时,我们可能会面临两个主要问题 文件。

我有假人。json文件在我的项目中,我试图从该文件中获取json数据,但我得到了两个错误:

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

我在Chrome或任何浏览器的网络选项卡中的响应中得到了一个HTML文件而不是实际的JSON数据。

下面是解决我的问题的两个主要原因。

JSON文件中的JSON数据无效。 这可能是JSON文件没有正确加载,所以你只是重新启动你的React服务器。这是我在React中的问题。

React直接运行或访问公用文件夹,而不是src文件夹。

我是怎么解决的:

我把我的文件移动到公共文件夹和访问是直接在src文件夹的任何文件。

在Redux action.js中调用REST:

export const fetchDummy = ()=>{
return (dispatch)=>{
        dispatch(fetchDummyRequest());
        fetch('./assets/DummyData.json')
        .then(response => {
            if (!response.ok) {
                throw new Error("HTTP error " + response.status);
            }
            return response.json();
        })
        .then(result => {
            dispatch(fetchDummySuccess(result))
        })
        .catch(function (err) {
          dispatch(fetchDummyFailure(err))
        })
    }
}

其他回答

在大多数情况下,我得到这个错误,当API抛出一个文本格式的错误。 我的建议是查看错误文本内容,以找出发生了什么错误。

jQuery = > set dataType: 'text' fetch = > response .text()代替response .json()

正如其他答案所描述的那样,畸形的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
  });
});

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

我的情况下,错误是由于我没有分配我的返回值给一个变量。产生错误信息的原因如下:

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

我把它改成:

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

如果没有变量,JSON将无法正确格式化数据。

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

这可能是旧的。但在Angular中,请求和响应的内容类型在我的代码中是不同的。检查标题

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

React axios

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

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