CORS django'Access-Control-Allow-Origin'

Dav*_*ern 4 django ajax jquery 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;
        }
  });
Run Code Online (Sandbox Code Playgroud)

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

我使用以下代码来设置标头:

response = JsonResponse(simpleWeek)
response['Access-Control-Allow-Origin'] = '*'
return response
Run Code Online (Sandbox Code Playgroud)

希望得到一些帮助!

T. *_*tal 7

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

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