javascript - create-react-app Uncaught (in promise) 语法错误 : Unexpected token < in JSON at position 0

标签 javascript json reactjs highcharts

尝试使用 React 中的 Highcharts 从 json 中动态读取数据。认输并向 SO 寻求帮助。

继续获取:

"Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0"

无论我把文件放在哪里。从 create-react-app 中退出并更改 Webpack 配置没有任何帮助。

网络选项卡显示 200 响应。

JSON 有效。已尝试从 srcpublic 文件夹中读取 json。已尝试使用带 header 和不带 header 的 fetch。 (与 header 一起使用会将 200 更改为 404)。

headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
  }
}

console.log(response.headers.get('Content-Type'))

返回文本/html; charset=UTF-8.

已尝试解决方案 herehere .

组件如下:

图表.js

import React, { Component } from 'react';
import HighchartsReact from 'highcharts-react-official';
import Highcharts from 'highcharts';

const endpoint = '../public/dummy.json'

export default class Chart extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // To avoid unnecessary update keep all options in the state.
      chartOptions: {
        chart: {
          type: 'bar'
        },
        xAxis: {
          title: {
            text: 'X Axis'
          }
        },
        yAxis: {
          title: {
            text: 'Y Axis'
           },
          min: 0,
          max: 100
        },
        series: [
          { data: [6] }
        ],
        plotOptions: {
          series: {
            point: {
              events: {
                mouseOver: this.setHoverData.bind(this)
              }
            },
            name: 'Chart name'
          }
        }
      },
      hoverData: null
    };
  }

  setHoverData = (e) => {
    console.log(e)
    // The chart is not updated because `chartOptions` has not changed.
    this.setState({ hoverData: e.target.options.x })
  }

  updateSeries = () => {
    // The chart is updated only with new options.
    this.setState({
      chartOptions: {
        series: [
          { data: [Math.random() * 100]}
        ]
      }
    });
  }


    componentDidMount() {
      // fetch(endpoint, {
      //   headers: {
      //     'Accept': 'application/json',
      //     'Content-Type': 'application/json'
      //   }
      // })
      fetch(endpoint)         
      .then((response) => {
        response.json()
        console.log(response.headers.get('Content-Type'))
      })
      .then(data => {
        this.state.chartOptions.series[0].data = data;
        this.setState({ data: data });
      })
      // .catch(error => {
      //   console.log('Error! ', error)
      // })
    }


  render() {
    const { chartOptions, hoverData } = this.state;

    console.log('this.state: ', this.state)

    return (
      <div>
        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />
      <h3>Hovering over {hoverData}</h3>
      <button onClick={this.updateSeries.bind(this)}>Update Series</button>
      </div>
    )
  }
}

虚拟.json

[
    {
        "first_name": "John",
        "amount": 10
    }, 
    {
        "fist_name": "Tim",
        "amount": 8 
    }
]

索引.js

import ReactDOM from 'react-dom';
import Chart from './Chart'

ReactDOM.render(<Chart />, document.getElementById('root'));

最佳答案

简答题

将 ../public/dummy.json 更改为 ./dummy.json 因为您是相对于公共(public)文件夹的根级别,而不是在同级文件夹内以公开src/文件夹。

详细解释

仅将路径设置为 ./dummy.json,因为只有公用文件夹中的内容才会被提供。您的 react 组件被捆绑到链接到公共(public)文件夹中的 index.html 的 js 文件中。因此,您的提取请求被捆绑/“编译”到公共(public)文件夹中的 JS 文件中。因此,您的相对文件路径应该假设您在公用文件夹中。

关于javascript - create-react-app Uncaught (in promise) 语法错误 : Unexpected token < in JSON at position 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516635/

相关文章:

javascript检测在文本区域中输入了一个字符串

json - 下载集合并导入到 mongo

c# - c# 和 newtonsoft 中的 JSON 日期和日期时间序列化

javascript - 为什么我的筛子没有看到应有的性能提升?

javascript - GraphQL - 将非特定对象的对象作为参数传递

javascript - 强制数据表列在小屏幕上占据全宽

python - row_to_json 和 psycopg2.fetchall() 结果是列表中的列表而不是列表中的字典

reactjs - React DnD - 如何获取拖动项目的ID

javascript - 如何使用 React-final-form 将 FieldArray 功能嵌套在其他 <FieldArray> 组件中

reactjs - Flow 会取代 PropTypes 吗?