Search code examples
javascriptajaxdjangophonegap

No 'Access-Control-Allow-Origin' header is present on the requested resource even though it is present


I am building an application with Django + Phonegap. When I try to send an Ajax Request using this function:

<script>
        $.ajax({
        url: "http://192.168.0.101/commerce/product/" + localStorage.getItem("toView"),
        type: "GET",
        data: {},

        success: function (json) {

            console.log(json);

        }

        });
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

I get an error saying in the Chrome console:

XMLHttpRequest cannot load http://192.168.0.101/commerce/product/2. Redirect from 'http://192.168.0.101/commerce/product/2' to 'http://192.168.0.101/commerce/product/2/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.101:3000' is therefore not allowed access.

The problem is in the fact that I am including the requested header. When I open the given URL in chrome and see the server response, I get this.

HTTP/1.0 200 OK
Date: Tue, 16 May 2017 09:42:29 GMT
Server: WSGIServer/0.2 CPython/3.4.3
Content-Type: application/json
Access-Control-Allow-Origin: *
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Methods: OPTIONS,GET,PUT,POST,DELETE
Access-Control-Allow-Headers: X-Requested-With, Content-Type
Content-Length: 89

I am also including my server code in views.py.

def product(request, prod_id):

    #### SOME CODE

    response = JsonResponse(response_data)
    response['Access-Control-Allow-Origin'] = '*'
    response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE'
    response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type'

    return response

Why am I getting this error? Please help. Thanks.


Solution

  • You should add a slash at the end of url in the ajax request:

    url: "http://192.168.0.101/commerce/product/" + localStorage.getItem("toView") + '/',
    

    Django expects a trailing slash to be appended to the URL.