本文介绍了“没有'Access-Control-Allow-Origin'标题存在”与Cherrypy错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在HTML页面中有以下javascript
I have the following javascript in a HTML page
<script>
function getContent(page)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = xmlhttp.responseText;
obj = JSON.parse(json);
document.getElementById("content").innerHTML=obj.content;
document.getElementById("title").innerHTML=obj.title;
}
}
xmlhttp.open("GET","http://differentserver.com:8080?page="+page,true);
xmlhttp.send();
}
</script>
以及使用cherrypy提供JSON的python脚本,其代码为:
and a python script using cherrypy that serves JSON, the code of which is:
import cherrypy
import json
class ContentGeneratorService(object):
exposed = True
@cherrypy.tools.accept(media='text/plain')
def GET(self, page='home'):
file_title = open(page + '.title', 'r')
file_content = open(page + '.content', 'r')
return json.dumps({"title": file_title.read().replace('\n', ''), "content": file_content.read().replace('\n', '') })
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == '__main__':
conf = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.sessions.on': True,
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'text/plain')],
}
}
cherrypy.server.socket_host = '0.0.0.0'
cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
cherrypy.config.update({'server.socket_port': 8080})
cherrypy.quickstart(ContentGeneratorService(), '/', conf)
然而,我得到一个没有'Access-Control-Allow-Origin'标题存在错误。有没有办法使用cherrypy启用CORS?
However, I get a "no 'Access-Control-Allow-Origin' header is present" error. Is there a way to enable CORS with cherrypy?
谢谢。
推荐答案
It seems to work now. I added
'tools.CORS.on': True
到conf。
这篇关于“没有'Access-Control-Allow-Origin'标题存在”与Cherrypy错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!