【问题标题】:“no 'Access-Control-Allow-Origin' header is present” error with CherrypyCherrypy 出现“不存在‘Access-Control-Allow-Origin’标头”错误
【发布时间】:2015-01-24 07:22:10
【问题描述】:

我在 HTML 页面中有以下 javascript

<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脚本,其代码为:

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?

谢谢。

【问题讨论】:

    标签: javascript python json cherrypy


    【解决方案1】:

    cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"

    风险很大,因为现在任何站点都可以对您的服务器进行 AJAX 调用并获取 python 脚本提供的内容。而是使用

    cherrypy.response.headers["Access-Control-Allow-Origin"] = "你的网站 域”

    是一个非常安全的选择。

    【讨论】:

      【解决方案2】:

      现在看来可以了。我加了

      'tools.CORS.on': True
      

      去确认。

      【讨论】:

      • 你在哪里添加的?在配置文件的哪个部分。全局或/
      • 这不再适用于当前的 CherryPy 版本 (10.2.1)。
      • 是的,对于 CherryPy 10 及更高版本,您还需要此配置:'tools.response_headers.on': True
      猜你喜欢
      • 2014-11-02
      • 2017-11-30
      • 2022-07-03
      • 2016-11-06
      • 1970-01-01
      • 2014-01-20
      • 2018-10-28
      • 2021-11-11
      • 2014-01-10
      相关资源
      最近更新 更多