3

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.

3
  • Full response with response headers and request headers would be more helpful. @noel please attach them upon availability Commented Aug 17, 2018 at 10:37
  • The Response I was able to print in the console is the following. 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(), … } code Im 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 99code Commented Aug 17, 2018 at 10:55
  • DRF typically returns HTML content when you get an error server-side (404, 500...) which your client-side JSON then cannot parse, giving you the error message you're seeing. To help you debug, can you show the relevant parts of url.py and your views.py? Commented Aug 17, 2018 at 11:34

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

The goal here is to get an javascript object looking like this: code data = { "questions":"127.0.0.1:8000/api/questions/?format=json", "choices":"127.0.0.1:8000/api/choices/?format=json" } code Im trying to get it work with this more simple api first of all.
Can you console.log the res constant before you parse it to json??
It logs: codeResponse { type: "basic", url: "localhost:3000/127.0.0.1:8000/api/?format=json", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false }code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.