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.
codeResponse bodyUsed: true headers: Headers <prototype>: HeadersPrototype { append: append(), delete: delete(), get: get(), … } ok: true redirected: false status: 200 statusText: "OK" type: "basic" url: "localhost:3000/127.0.0.1:8000/api/?format=json" <prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }codeIm not sure how to get the header, but my server logs this:code[17/Aug/2018 10:52:49] "GET /api/ HTTP/1.1" 200 99codeurl.pyand yourviews.py?