How to call Django REST APIs using javascript/jquery/AJAX?

假如想象 提交于 2019-12-06 05:51:04

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!