CORS django“访问控制允许来源" [英] CORS django 'Access-Control-Allow-Origin'

查看:120
本文介绍了CORS django“访问控制允许来源"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使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.

I was trying to get a CORS request working. With the following JS code I get this error: 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'标头.但是,当我手动加载该网站时,它就存在了!

When I look at the network using chrome's devtools I see that there is no 'Access-Control-Allow-Origin' header indeed. But when I load the site manually it is present!

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

I used the following code to set the headers:

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

希望获得帮助!

推荐答案

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

It says No 'Access-Control-Allow-Origin' header is present on the requested resource. which means your server application needs tunning to accept cross origin requests. Cross origin requests are by default not working due to security reasons. You need to enable them.

对于django,有一个维护良好的程序包,它为此设置了很多: https://github.com/ottoyiu/django-cors-headers/

For django there is a maintained package with good amount of settings just for this: https://github.com/ottoyiu/django-cors-headers/

这篇关于CORS django“访问控制允许来源"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆