Django Rest Framework+ReactJS:我的API有什么问题?

2024-05-19 22:10:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用“ReactJS”从djangorest framework API获取数据,但我始终面临相同的错误:

SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

我认为真正的问题是在我的API中,因为我已经尝试了3种不同的方法来让数据生效。也许有人知道我可以对我的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" }

我用来检索数据的ReactComponent如下所示:

API的标题如下所示:

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和我的客户机一定是不兼容的。在


Tags: 数据apijsonformathttp客户机frameworkcontent
2条回答

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

这里的问题是,根据同源策略,浏览器阻止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

您似乎没有查询有效的路由,请尝试以下操作:

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

相关问题 更多 >