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
}
});
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.
来源:https://stackoverflow.com/questions/37948991/how-to-call-django-rest-apis-using-javascript-jquery-ajax