如果像下面这样只是在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): def __init__(self, response=None, **kwargs): kwargs[‘headers‘] = ‘‘ headers = kwargs.get(‘headers‘) # 跨域控制 origin = (‘Access-Control-Allow-Origin‘, ‘*‘) header = (‘Access-Control-Allow-Headers‘, ‘Content-Type‘) methods = (‘Access-Control-Allow-Methods‘, ‘HEAD, OPTIONS, GET, POST, DELETE, PUT‘) if headers: headers.add(*origin) headers.add(*header) headers.add(*methods) else: headers = Headers([origin, header, methods]) kwargs[‘headers‘] = headers return super().__init__(response, **kwargs)需要注意的是这里的header = (‘Access-Control-Allow-Headers‘, ‘Content-Type‘)如果没加这一行,很可能会出现只发送了OPTIONS请求,成功后却没有发送GET/POST等请求
这里的值根据前端请求的header内容的,如果前端的header中还有authorization,那么这里得把authorization也加上header = (‘Access-Control-Allow-Headers‘, ‘Authorization, Content-Type‘)
最后在调用该类
app = Flask(__name__)
app.response_class = MyResponse
原文地址:https://www.cnblogs.com/tyrionyang/p/9089661.html
时间: 2024-10-28 15:09:20