且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django Rest Framework:XML​​HttpRequest无法加载http://127.0.0.1:8000/xyz/api/abc

更新时间:2023-10-27 20:13:52

TL; DR

将您的AJAX请求发送到带有斜杠的URL.

Issue your AJAX request to a slash-appended URL.

说明

在我们讨论之后,罪魁祸首似乎是Django的自动APPEND_SLASH = True,当启用CommonMiddleware时启用.

After our discussion, it appears that the culprit is Django's automatic APPEND_SLASH = True which is enabled when CommonMiddleware is enabled.

这会导致来自Angular应用程序的AJAX请求首先命中301 Moved Permanently重定向到斜杠添加的URL.但是,corsheaders中间件不对此响应起作用,因此浏览器抱怨缺少Access-Control-Allow-Origin标头.

This causes the AJAX request from your Angular app to first hit a 301 Moved Permanently redirect to the slash-appended URL. However, the corsheaders middleware does not act on this response, so the browser complains about a missing Access-Control-Allow-Origin header.

可以通过直接请求带有斜杠的URL并完全绕过301重定向来解决此问题.

This is solved by requesting the slash-appended URL directly, and bypassing the 301 redirect altogether.

$http({
    method: 'GET',
    url: 'http://127.0.0.1:8000/xyz/api/abc/',  // trailing slash here
    cache: false
}).success(...);