3

I'm trying to connect my Django backend to a React Frontend using axios to access the api endpoint. I have tested the api using curl to see if I receive a json of the test data, it is fine. I have opened up the endpoint so that it does not need authentication. But I keep on getting this error in my javascript console:

edit: for to say that I am running the api and frontend on my computer

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)

Test.js- Test component to test out feeding backend to frontend. I would like to console log the data but only catch the error.

import React, {Component} from 'react'
import axios from 'axios';

class Test extends Component{
  constructor(){
    super();
    this.state = {
      messages:[],
    }
  }
  componentDidMount(){
    axios.get('http://127.0.0.1:8000/api/message/?format=json')
      .then(res=> {
        console.log(res);
      })
      .catch(error =>{
        console.log(error);
      });
}
  render(){
    return(
      <div>
        <h1>
          Message:
        </h1>
      </div>
    )
  }
}


export default Test;

1 Answer 1

2

I needed to setup CORS on my django api. The issue was not with my front end but by backend not being setup properly. Whenever you have api request from a different server you have to setup CORS on the backend.

Sign up to request clarification or add additional context in comments.

1 Comment

provide code examples homie

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.