Reputation: 41
I'm trying to fetch data from a django
rest-framework API, using `ReactJS' but I keep facing the same error:
SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
I think the actual problem is is in my API, since I have already tried 3 different approaches to get the data into React. Maybe somebody knows what I can do to my API to make it work? Im using the djangorestframework
library. The API looks as following:
{
"questions":"http://127.0.0.1:8000/api/questions/?format=json",
"choices":"http://127.0.0.1:8000/api/choices/?format=json"
}
And the React
Component
I'm using to retreive the data is the following:
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;
The Header of the API looks like that:
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
I tried the following example API with my client and it worked: https://jsonplaceholder.typicode.com/todos/1
So something about djangorestframework and my client must be incompatible.
Upvotes: 3
Views: 802
Reputation: 41
Solution: needed to add Cross Origin Resource Sharing (CORS)
The Problem here was, that Browsers prevent Javascript from reaching out to other domains according to the Same origin Policy.
The default workaround for this in Django, is "django-cors-headers". To install it:
pip install django-cors-headers
Then it can be activated in the settings.py
Writing:
INSTALLED_APPS = (
##...
'corsheaders'
)
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
#...
)
CORS_ORIGIN_ALLOW_ALL = True
Upvotes: 1
Reputation: 1140
You do not seem to query a valid route, perhaps try following:
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"
}
}
Upvotes: 0