我正在尝试使用“ReactJS”从 django
rest-framework API 获取数据,但我一直面临同样的错误:
SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
我认为实际问题出在我的 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 的某些东西和我的客户端一定是不兼容的。
最佳答案
解决方案:需要添加跨域资源共享(CORS)
这里的问题是,浏览器根据 同源策略 阻止 Javascript 访问其他域。
Django 中的默认解决方法是“django-cors-headers”。 安装它:
pip 安装 django-cors-headers
然后就可以在settings.py
写作:
INSTALLED_APPS = (
##...
'corsheaders'
)
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
#...
)
CORS_ORIGIN_ALLOW_ALL = True
关于javascript - Django Rest 框架 + ReactJS : Whats wrong with my API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51893045/