如何使用javascript/jquery/AJAX调用Django REST API? [英] How to call Django REST APIs using javascript/jquery/AJAX?
问题描述
我想使用Javascript,jQuery,AJAX在Frontend中调用Django Rest API. Request方法是POST,但是当我看到API调用其调用OPTIONS方法时.因此,我开始了解access-control-allow-origin
,我想应该在API中允许使用access-control-allow-origin
.为此,我使用了django-CORS-headers
包,但仍然调用了OPTIONS
方法.
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.
代码是这样的:
jQuery.ajax({
url: API_url,
headers:headers,
dataType: "JSON",
type: "POST",
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function( response, jqXHR ) {
do something here
}
});
推荐答案
好吧,我早就学会了这个答案,但是忘记了我当时发布了这个问题!
因此,无论何时在两个应用程序之间发出http请求,浏览器都会先执行OPTION
请求,以检查该应用程序是否已通过身份验证以向另一个应用程序发出请求.如果身份验证失败,则不会发送其他任何请求.这就是为什么如果您向api发送邮递员请求,它将在不启用cors的情况下工作的原因.因此,要使跨源请求正常工作,请在Django settings.py
中设置键CORS_ORIGIN_ALLOW_ALL = True
以为所有域启用CORS.要将指定的域列入白名单,请设置
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 .:您必须使用django-CORS-header
软件包.
P.S.: You have to use django-CORS-header
package.
这篇关于如何使用javascript/jquery/AJAX调用Django REST API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!