如何使用 javascript/jquery/AJAX 调用 Django REST API?

Asi*_*ngh 5 python django ajax jquery django-cors-headers

我想在前端使用 Javascript、jQuery、AJAX 调用 Django Rest API。请求方法是 POST 但当我看到 API 调用它的调用 OPTIONS 方法时。所以,我开始知道access-control-allow-origin我猜需要在 API 中允许哪些。为此,我使用了django-CORS-headers包,但仍然调用了该OPTIONS方法。

代码是这样的:

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

Asi*_*ngh 0

好吧,我很久以前就知道了这个答案,但忘记了我当时发布了这个问题!因此,每当两个应用程序之间发出 http 请求时,浏览器都会OPTION首先发出请求,以检查该应用程序是否经过身份验证,以便向另一个应用程序发出请求。如果身份验证失败,则不会发送其他请求。这就是为什么如果您向 api 发出 postman 请求,它无需启用 cors 即可工作。因此,为了使跨源请求能够工作,请CORS_ORIGIN_ALLOW_ALL = True在 django 中设置密钥settings.py以便为所有域启用 CORS。将指定域设置为白名单

CORS_ORIGIN_ALLOW_ALL = False,

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

PS:你必须使用django-CORS-header包。