Python 使用Phonegap访问时Django应用程序中的Access-Control-Allow-Origin
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22355540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access-Control-Allow-Origin in Django app when accessed with Phonegap
提问by Sascuash
I'm developing a Phonegap app for my Django based app, but when trying to make Ajax calls I get this error:
我正在为基于 Django 的应用程序开发 Phonegap 应用程序,但是在尝试进行 Ajax 调用时出现此错误:
XMLHttpRequest cannot load http://domain.herokuapp.com/getcsrf/?tags=jquery%2Cjavascript&tagmode=any&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
How can I make it so my Django app allows cross origin for some urls?
我怎样才能让我的 Django 应用程序允许某些 url 跨源?
Here's my Ajax code:
这是我的 Ajax 代码:
get: function() {
$.getJSON("http://domain.herokuapp.com/getcsrf/",
{
tags: "jquery,javascript",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(item){
console.log(item);
});
});
}
采纳答案by stormlifter
Django by default does not provide the headers necessary to provide cross origin. The easiest way would be to just use this Django app that handles it for you: https://github.com/ottoyiu/django-cors-headers
默认情况下,Django 不提供提供跨源所需的标头。最简单的方法是使用这个为你处理它的 Django 应用程序:https: //github.com/ottoyiu/django-cors-headers
You can then set whichever domains you want white listed using the settings
然后,您可以使用设置来设置您想要列入白名单的任何域
CORS_ORIGIN_WHITELIST = (
'google.com',
'hostname.example.com'
)
to support allowing all, just use the setting...
CORS_ORIGIN_ALLOW_ALL = Trueand then do any filtering of the request in middleware or in the view.
要支持全部允许,只需使用设置...
CORS_ORIGIN_ALLOW_ALL = True然后在中间件或视图中对请求进行任何过滤。
回答by mariusz_latarnik01
For single views you can manually add headers:
对于单个视图,您可以手动添加标题:
@require_GET
def api_getto(request):
response = JsonResponse(
# your stuff here
)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response["Access-Control-Max-Age"] = "1000"
response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type"
return response

