How do I set response headers in Flask?

前端 未结 5 1631
北海茫月
北海茫月 2020-11-27 14:32

This is my code:

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


        
5条回答
  •  情深已故
    2020-11-27 15:08

    Use make_response of Flask something like

    @app.route("/")
    def home():
        resp = make_response("hello") #here you could use make_response(render_template(...)) too
        resp.headers['Access-Control-Allow-Origin'] = '*'
        return resp
    

    From flask docs,

    flask.make_response(*args)

    Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

提交回复
热议问题