更新时间: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(...);