5

I want to call a Django Rest API in Frontend using Javascript, jQuery, AJAX. Request method is POST but when I see the API call its calling OPTIONS method. So, I came to know about access-control-allow-origin which needs to be allowed in APIs I guess. For that I used django-CORS-headers package but still its calling the OPTIONS method.

code is something like this :

jQuery.ajax({
            url: API_url,
            headers:headers,
            dataType: "JSON",
            type: "POST",
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            success: function( response, jqXHR ) {
                    do something here
            }
});

1 Answer 1

0

Well, I learnt this answer a long time back but forgot that I had posted this question then! So, Whenever an http request is made between two applications, browser does a OPTION request first to check whether the application is authenticated to make a request to the other application or not. If authentication fails, no other requests are sent. That's why if you do a postman request to an api, it will work without enabling the cors. So, to enable the cross origin request to work, Set key CORS_ORIGIN_ALLOW_ALL = True in django settings.py for enabling CORS for all domains. To whitelist specified domains set

CORS_ORIGIN_ALLOW_ALL = False,

CORS_ORIGIN_WHITELIST = ('http//:localhost:8000')

P.S.: You have to use django-CORS-header package.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.