通过Phonegap访问时Django应用中的Access-Control-Allow-Origin [英] Access-Control-Allow-Origin in Django app when accessed with Phonegap
问题描述
我正在为基于Django的应用程序开发Phonegap应用程序,但是在尝试进行Ajax调用时出现此错误:
I'm developing a Phonegap app for my Django based app, but when trying to make Ajax calls I get this error:
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.
如何做到这一点,以便我的Django应用允许某些URL的跨源访问?
How can I make it so my Django app allows cross origin for some urls?
这是我的Ajax代码:
Here's my Ajax code:
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);
});
});
}
推荐答案
默认情况下,Django不提供提供交叉原点所必需的标头.最简单的方法是只使用为您处理此Django应用程序: https://github.com/ottoyiu/django -cors-headers
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
然后您可以使用设置来设置要白名单的任何域
You can then set whichever domains you want white listed using the settings
CORS_ORIGIN_WHITELIST = (
'google.com',
'hostname.example.com'
)
要支持全部允许,只需使用设置...
CORS_ORIGIN_ALLOW_ALL = True
然后在中间件或视图中对请求进行任何过滤.
to support allowing all, just use the setting...
CORS_ORIGIN_ALLOW_ALL = True
and then do any filtering of the request in middleware or in the view.
这篇关于通过Phonegap访问时Django应用中的Access-Control-Allow-Origin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!