Flask restful API如何解决跨站请求问题
如果像下面这样只是在return的response添加header是不行的:
response = make_response(jsonify(response=get_articles(ARTICLES_NAME)))
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST'
response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
return response
原因是因为发送请求前都会有一个OPTIONS请求,OPTIONS是客户端浏览器进行的HTTP跨域预访问,而OPTIONS请求时Flask会自动的返回Response,原生的Response并没有处理跨站请求问题,所以即使在API中的Response添加了header也是不行的。
那么解决办法就是:Customizing the Flask Response Class
class MyResponse(Response):<br /> def __init__(self, response=None, **kwargs):<br /> kwargs['headers'] = ''<br /> headers = kwargs.get('headers')<br /> # 跨域控制<br /> origin = ('Access-Control-Allow-Origin', '*')<br /> header = ('Access-Control-Allow-Headers', 'Content-Type')<br /> methods = ('Access-Control-Allow-Methods', 'HEAD, OPTIONS, GET, POST, DELETE, PUT')<br /> if headers:<br /> headers.add(*origin)<br /> headers.add(*header)<br /> headers.add(*methods)<br /> else:<br /> headers = Headers([origin, header, methods])<br /> kwargs['headers'] = headers<br /> return super().__init__(response, **kwargs)<br />需要注意的是这里的header = ('Access-Control-Allow-Headers', 'Content-Type')<br />如果没加这一行,很可能会出现只发送了OPTIONS请求,成功后却没有发送GET/POST等请求
这里的值根据前端请求的header内容的,如果前端的header中还有authorization,那么这里得把authorization也加上<em><br />header = ('Access-Control-Allow-Headers', 'Authorization, Content-Type')<br /></em>
最后在调用该类
app = Flask(__name__)
app.response_class = MyResponse
相关推荐
hzyuhz 2020-07-04
washing 2020-05-29
JessePinkmen 2020-05-01
bestallen 2020-08-17
JessePinkmen 2020-07-26
washing 2020-07-18
hzyuhz 2020-06-28
hzyuhz 2020-06-25
苦咖啡flask 2020-06-25
苦咖啡flask 2020-06-25
苦咖啡flask 2020-06-18
washing 2020-06-16
liuweiq 2020-06-14
wushaojun 2020-06-14
JessePinkmen 2020-06-14
kgshuo 2020-06-14
JessePinkmen 2020-06-14