添加http响应头

时间:2018-01-01 02:15:05

标签: javascript html heroku

我已经在python中用Heroku编写了一个Web应用程序,并希望授予javascript客户端对我的资源的基本访问权限。我一直在阅读这篇文章:https://www.w3.org/wiki/CORS_Enabled

从文章中我发现我应该做以下事情:

print("Content-Type: text/turtle")
print("Content-Location: mydata.ttl")
print("Access-Control-Allow-Origin: *")

procfile如下:web: python app.py
和app.py如下:

#!/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))

但是我仍然无法访问资源,我收到此错误:

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.

感谢您的帮助

#!/usr/bin/env python
import gevent.monkey
gevent.monkey.patch_all()
import bottle
import os
@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))

@thmsdnnr,这似乎有效,谢谢

1 个答案:

答案 0 :(得分:1)

您需要使用response.set_header

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")

如果您发现自己在许多路线上都这样做,可以设置'after_request'钩子like this