CORS django 'Access-Control-Allow-Origin'

CORS django 'Access-Control-Allow-Origin'

我试图让 CORS 请求正常工作。使用以下 JS 代码我得到这个错误:XMLHttpRequest cannot load http://localhost:65491/?token=u80h9kil9kjuu02539buak4r6n&user=~me. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:50303' is therefore not allowed access.

这是JS代码:

$.ajax({
     url: "http://localhost:60906/",
     data: {token : 'u80h9kil9kjuu02539buak4r6n', user : '~me'},
     type: "GET",
     crossDomain: true,
     success: function( response ) {
         alert('Success!' + response);
         var context = response;
        }
  });

当我使用 chrome 的开发工具查看网络时,我发现确实没有 'Access-Control-Allow-Origin' header。但是当我手动加载网站时,它就存在了!

我使用以下代码设置 headers:

response = JsonResponse(simpleWeek)
response['Access-Control-Allow-Origin'] = '*'
return response

希望得到一些帮助!

它说 No 'Access-Control-Allow-Origin' header is present on the requested resource. 这意味着您的服务器应用程序需要调整以接受跨源请求。 出于安全原因,跨源请求默认情况下不起作用。您需要启用它们。

对于 django 有一个维护包,其中包含大量设置:https://github.com/ottoyiu/django-cors-headers/

经过 2 小时的故障排除后,我找到了解决方案:url 中的 TYPO。 检查两次,也许它也能解决您的问题。

要让这个东西起作用,你需要做两件事:


  • 而不是 https:// 只需在 CORS_ORIGIN_WHITELIST 中输入 http://settings.py

  • 在同一文件中添加CORS_ORIGIN_ALLOW = True