crodev
crodev

Reputation: 1491

"Network Error" with Axios and DjangoREST but request succeeds at the end

So, I am using ReactJS and DjangoRESTframework to build my app.
Now..when I send a request with Postman it works perfectly(ex. 127.0.0.1:8000/api/users/ GET request) and when I try to do it in React with Axios I get a network error but on my local development server console I see that it succeeded.

This is my get request with axios in react:

componentDidMount() {
    axios.get('http://127.0.0.1:8000/api/users/', {
      headers: {
        'Accept': 'application/json'
      }
    })
    .then(res => {
      console.log(res.data);
    }).catch(err => {
      console.log(err);
    })
  }

And I get an Network Error. But as I said with Postman it works.

One more example is that I send POST request with Axios to http://127.0.0.1:8000/api/users/ and as response I get Network Error as well but on my backend, user IS created.

This is code for my POST request with axios:

let formData = new FormData();
      formData.set('email', this.state.emailField);
      formData.set('username', this.state.usernameField);
      formData.set('password', this.state.passwordField);
      axios({
        method: 'POST',
        data: formData,
        url: 'http://127.0.0.1:8000/api/users/',
        config: {headers: {'Content-Type': 'multipart/form-data'}}
      }).then(request => {
        console.log(request.data);
      }).catch(err => {
        console.log(err);
      })

I googled for about an hour to fix this but nothing helps.

Upvotes: 2

Views: 2995

Answers (1)

Tridev Mishra
Tridev Mishra

Reputation: 391

Can you be more clear on what you see as Network error? Attach some error messages / Stack trace.

This looks like a Cross-Origin Resource Sharing (CORS) issue to me. Try configuring CORS on your DjangoRESTframework backend.

This might help you if that is the case.

Upvotes: 1

Related Questions