小编典典

如何在Flask中设置响应头?

flask

这是我的代码:

@app.route('/hello', methods=["POST"])
def hello():
    resp = make_response()
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

但是,当我从浏览器向服务器发出请求时,出现此错误:

XMLHttpRequest cannot load http://localhost:5000/hello. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

我也尝试过这种方法,在请求之后设置响应头:

@app.after_request
def add_header(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

没有骰子。我犯了同样的错误。有没有一种方法可以只在route函数中设置响应头?这样的事情将是理想的:

@app.route('/hello', methods=["POST"])
    def hello(response): # is this a thing??
        response.headers['Access-Control-Allow-Origin'] = '*'
        return response

但我还是找不到这样做。请帮忙。

编辑

如果我使用POST请求卷曲URL,如下所示:

curl -iX POST http://localhost:5000/hello

我得到这个回应:

HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/html
Content-Length: 291
Server: Werkzeug/0.9.6 Python/2.7.6
Date: Tue, 16 Sep 2014 03:58:42 GMT

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request.  Either the server is overloaded or there is an error in the application.</p>

有任何想法吗?


阅读 2302

收藏
2020-04-05

共1个答案

小编典典

你可以很容易地做到这一点:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

查看flask.Responseflask.make_response()

但是有些事情告诉我你还有另一个问题,因为该软件也after_request应该正确处理它。

编辑
我刚刚注意到你已经在使用make_response哪种方法来做到这一点。就像我之前说过的,after_request应该也可以。尝试通过curl到达端点,看看标题是什么:

curl -i http://127.0.0.1:5000/your/endpoint

你应该看到

> curl -i 'http://127.0.0.1:5000/'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 11
Access-Control-Allow-Origin: *
Server: Werkzeug/0.8.3 Python/2.7.5
Date: Tue, 16 Sep 2014 03:47:13 GMT

注意Access-Control-Allow-Origin标头。

编辑2
正如我所怀疑的,你得到500,所以你没有按照你的想法设置标题。app.debug = True在启动应用程序之前尝试添加,然后重试。你应该获得一些输出,以显示问题的根本原因。

例如:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    user.weapon = boomerang
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

给出格式正确的html错误页面,该页面位于底部(有助于curl命令)

Traceback (most recent call last):
...
  File "/private/tmp/min.py", line 8, in home
    user.weapon = boomerang
NameError: global name 'boomerang' is not defined
2020-04-05