Forums

Error 401 Authorization Required on fetch(GET) request from another origin (django-cors-headers)

I am trying to make a fetch request from a Shopify theme (JS) to an app hosted on PythonAnywhere but I get a 401 Authorization Required response on the Preflight request.

It works when I expose the same Django app through ngrok hosted on my local but it doesn't through pythonanywhere.

I'm using the django-cors-headers package for this with the following configurations in settings.py:

ALLOWED_HOSTS = [ '*' ]
CORS_ALLOWED_ORIGINS = [
     'http://***.myshopify.com',
     'https://***.myshopify.com'
]
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_METHODS = [
     'GET',
 ]

I am getting this response:

HTTP/1.1 401 Authorization Required
Date: Fri, 16 Sep 2022 14:50:01 GMT
Transfer-Encoding: chunked
Connection: keep-alive
WWW-Authenticate: Basic realm="Default Realm"
Server: PythonAnywhere

How can I get this to work under PythonAnywhere?

How do you handle authorization on myshopify?

I don't have any authorization logic implemented yet (Django or Shopify). It's a simple Django endpoint that should return some data on a GET request, without any additional parameters.

Here is the python code in Django:

def get(self, request, *args, **kwargs):
    # expand and implement security features
    try:
        data = get_some_data_from_the_database()
    except Exception as e:
        return JsonResponse({ "status": "error", "message": "Cannot get data" })
    return JsonResponse({ "status": 200, "message": "Success", "data": data })

Also this is the request code from Shopify using fetch:

fetch(DJANGO_URL, {
    method: 'GET',
    // mode: 'cors',
    // headers: { 'Access-Control-Allow-Origin': 'https://***.myshopify.com/', }
 })

or with XMLHttpRequest:

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      console.log(this);
      if (this.readyState == 4 && this.status == 200) {
          console.log("Success")
       }
   };
   xhttp.open("GET", DJANGO_URL);
   // xhttp.setRequestHeader('Access-Control-Allow-Origin', 'https://***.myshopify.com/')
   xhttp.send();

I've tried both with and got the same preflight response.

Do you have a username and password set on your web app?