简体   繁体   English

Flask 无法添加自定义标头

[英]Flask fails to add custom headers

I'm trying to return custom headers like this:我正在尝试返回这样的自定义标头:

@app.route("/generate", methods=['POST'])
def generate():
    # data is generated here
    resp = Response(jsonify(data))
    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Credentials'] = True
    return resp

But they don't seem to be present in the output.但它们似乎不存在于 output 中。 Changing status code to 201 as mentioned here didn't help either (I did this by adding status=201 to Responce construction).如此处提到将状态代码更改为 201 也无济于事(我通过将status=201添加到Responce构造中来做到这一点)。

Any bit of help would be appreciated.任何帮助将不胜感激。

EDIT 1: Added a bit to a code.编辑 1:在代码中添加了一些内容。 Solutions described here didn't work for me either. 这里描述的解决方案对我也不起作用。 Tried both Response and make_response , added @app.after_request as suggested - no effect.尝试了Responsemake_response ,按照建议添加了@app.after_request - 没有效果。 The only headers present are:唯一存在的标题是:

'Content-Type': 'application/json', 
'Content-Length': '113', 
'Server': 'Werkzeug/1.0.1 Python/3.7.7', 
'Date': 'Fri, 08 May 2020 17:05:38 GMT'

I think the problem is that, although you are adding custom headers, you are still returning a JSON object where you write resp = Response(jsonify(data)) .我认为问题在于,尽管您正在添加自定义标头,但您仍然返回 JSON object 您在其中编写resp = Response(jsonify(data)) It is possible that flask assingns the response headers automatically based on the response's body's format. flask 可能会根据响应正文的格式自动分配响应标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM