CORS django'Access-Control-Allow-Origin'

时间:2016-02-20 10:27:42

标签: jquery ajax django cors django-cors-headers

我试图让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的devtools查看网络时,我发现确实没有'Access-Control-Allow-Origin'标头。但是,当我手动加载网站时,它就出现了!

我使用以下代码设置标题:

response = JsonResponse(simpleWeek)
response['Access-Control-Allow-Origin'] = '*'
return response
希望得到一些帮助!

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:1)

经过2小时的故障排除后,我在网址中找到了解决方法: TYPO 。 请检查两次,也许它也可以解决您的问题。

答案 2 :(得分:0)

要使此功能正常运行,您需要做两件事:


  • 而不是https://,只需在 settings.py

  • CORS_ORIGIN_WHITELIST 中输入http://
  • 在同一文件中添加CORS_ORIGIN_ALLOW = True

相关问题