No 'Access-Control-Allow-Origin' header is present on the requested resource in Django application

434 views Asked by At

I am developing a django based application where I am using Json call from one application to another,the json call is from HTML file which is in AWS s3 bucket and the json call is from django application.

When I am running/opening the HTML file getting this error

XMLHttpRequest cannot load https://domain_name/email_view/6/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s3-ap-southeast-1.amazonaws.com' is therefore not allowed access. The response had HTTP status code 500.

My code to resolve this issue

$(document).ready(function () {

    $.get("url", function (data) {
       email_otp = JSON.stringify(data);
        "some code"
    }); 


});

views.py

def email_view(request, id):
course = get_object_or_404(CourseWare, pk=id)
user = UserProfile.objects.get(user__id=request.user.id)
myorder = MyOrder.objects.get_or_create(buyer=user, course=course)
if request.is_ajax():
        sms_otp = randint(10000, 100000)
        return HttpResponse(json.dumps(sms_otp),content_type="application/json")

nginx code

  location /media {                                                           
                root /opt/pursuite/www;                                         
                add_header Access-Control-Allow-Origin "*";                   
                add_header Access-Control-Allow-Methods "GET, OPTIONS";      
                add_header Access-Control-Allow-Methods "PUT, OPTIONS";         
                add_header Access-Control-Allow-Methods "GET,POST,OPTIONS,HEA
D";                                                                             
 add_header Access-Control-Allow-Headers "Authorization, Origin,
X-Requested-With, Content-Type, Accept";}                                                                             
1

There are 1 answers

1
Ced On

you need to enable cors on https://domain_name/email_view/6/

you did it there :

 location /media { ... }  

which doesn't seem to be the right location

I personnally don't know django but you can follow what's written in this link: