3

我正在尝试django使用“ReactJS”从 rest-framework API 获取数据,但我一直面临同样的错误:

SyntaxError:“JSON.parse:JSON 数据第 1 行第 1 列的意外字符”

我认为实际问题出在我的 API 中,因为我已经尝试了 3 种不同的方法将数据导入 React。也许有人知道我可以对我的 API 做些什么来使其工作?我正在使用djangorestframework图书馆。API 如下所示:

{
"questions":"http://127.0.0.1:8000/api/questions/?format=json",
"choices":"http://127.0.0.1:8000/api/choices/?format=json"
}

React Component用来检索数据的方法如下:

import React, { Component } from 'react';

class ApiFetch extends Component {
  state = {
    data: []
  };

  async componentDidMount() {
    try {
      const res = await fetch('127.0.0.1:8000/api/?format=json');
      const data = await res.json();
      this.setState({
        data
      });
      console.log(this.state.data)  
    } catch (e) {
      console.log(e);  //SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
    }
  }
  
  render() {
    return (
      <div>
        {(this.state.data)}
      </div>
    );
  }
}

export default ApiFetch;

API 的 Header 如下所示:

allow →GET, HEAD, OPTIONS
content-length →123
content-type →application/json
date →Fri, 17 Aug 2018 11:01:36 GMT
server →WSGIServer/0.2 CPython/3.6.3
vary →Accept, Cookie
x-frame-options →SAMEORIGIN

我用我的客户端尝试了以下示例 API,它工作正常: https ://jsonplaceholder.typicode.com/todos/1

所以关于 djangorestframework 和我的客户的东西一定是不兼容的。

4

2 回答 2

1

解决方案:需要添加跨域资源共享(CORS)

这里的问题是,浏览器会根据Same origin Policy阻止 Javascript 访问其他域。

Django 中的默认解决方法是“django-cors-headers”。要安装它:

pip install django-cors-headers

然后就可以在settings.py

写作:

INSTALLED_APPS = (
    ##...
    'corsheaders'
)
MIDDLEWARE_CLASSES = (
    'corsheaders.middleware.CorsMiddleware',
    #...
)

CORS_ORIGIN_ALLOW_ALL = True
于 2018-08-17T13:34:43.837 回答
0

您似乎没有查询有效的路线,也许尝试以下:

async componentDidMount() {
    try {
      const res = await fetch('127.0.0.1:8000/api/questions/?format=json');
      const data = await res.json();
      this.setState({
        data
      });
      console.log(this.state.data)  
    } catch (e) {
      console.log(e);  //SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
    }
  }
于 2018-08-17T10:12:15.203 回答