Heroku上Python Web应用CORS跨域配置问题求助
解决Heroku上Python Bottle应用的CORS跨域访问问题
我在Heroku平台上用Python开发了一款Web应用,想要让JavaScript客户端能访问我的资源,结果遇到了跨域访问的问题,下面是我的排查和解决过程:
问题现象
尝试访问应用时,浏览器抛出了CORS错误:
Failed to load https://ksmlgames.herokuapp.com/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
最初的错误尝试
我一开始参考CORS相关指导,在路由函数里直接用print()输出响应头,代码如下:
#!/usr/bin/env python import gevent.monkey gevent.monkey.patch_all() import bottle import os @bottle.route('/') def index(): print("Content-Type: text/turtle") print("Content-Location: mydata.ttl") print("Access-Control-Allow-Origin: *") return("testing") bottle.run(server='gevent', host='0.0.0.0', port=os.environ.get('PORT', 5000))
我的Procfile配置为:
web: python app.py
但这种方式完全无效——因为Bottle框架不会把print()的输出当作HTTP响应头发送,这些内容只会输出到应用的控制台日志里,根本不会被浏览器接收到。
正确的解决方法
后来我改用Bottle内置的response对象来设置响应头,修改后的代码如下:
#!/usr/bin/env python import gevent.monkey gevent.monkey.patch_all() import bottle import os # 必须导入bottle的response对象才能使用 from bottle import response @bottle.route('/') def index(): response.set_header("Content-Type", "text/turtle") response.set_header("Content-Location", "mydata.ttl") response.set_header("Access-Control-Allow-Origin", "*") return("testing") bottle.run(server='gevent', host='0.0.0.0', port=os.environ.get('PORT', 5000))
这里的关键是通过response.set_header()方法来设置HTTP响应头,这样浏览器才能正确接收到CORS相关的头信息,从而解决跨域访问的限制。
感谢@thmsdnnr确认这个修改后的版本可以正常工作。
内容的提问来源于stack exchange,提问作者Mathew
相关产品推荐
相关产品推荐

