0

I am using Django REST framework to create an API. It is working fine with cURL.

curl -H 'Accept: application/json; indent=4' -u ratan:qazwsxedc123 http://127.0.0.1:8000/api/grocery/subcategories/

However, when I try to use jQuery to populate a div in a HTML page it is not working, I am getting a 403 forbidden error.

This is my code.

$.ajax({
  url: "http://127.0.0.1:8000/api/grocery/subcategories/?format=json",
  type: "GET",
  dataType: "json",
  data: {
    username: "ratan",
    password: "qazwsxedc123"
  },
  success: function(data) {
    console.log('ratan');
  },
});

I thought it can be because of CORS, so I have tried django-cors-headers, but it didn't help.

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
  • try adding ```contentType: "application/json",``` as it looks like you're trying to send a json object. But then again in your CURL you are sending them in a header. – James111 Feb 24 '16 at 22:15
  • This really isn't a Django question. – Daniel Roseman Feb 24 '16 at 22:15
  • @DanielRoseman The problem was in his JS, but it's good to know all the details for context. He could have misconfigured his DRF somewhere. – Kieran Feb 24 '16 at 22:17

1 Answers1

1

You are passing your username and password incorrectly when making the request. This is discussed in this SO question.

Try this method instead.

$.ajax
({
  type: "GET",
  url: "http://127.0.0.1:8000/api/grocery/subcategories/?format=json",
  dataType: 'json',
  headers: {
    "Authorization": "Basic " + btoa("ratan:qazwsxedc123")
  },
  success: function (){
    console.log('ratan'); 
  }
});
Community
  • 1
  • 1
Kieran
  • 2,554
  • 3
  • 26
  • 38