flask跨域 blueprint跨域和restful跨域

tech2025-11-13  4

蓝图的跨域是用了flask-cors库中的CORS, 此方法跨域只处理装饰器式的路由, restful是继承Resource的所以该跨域并不能生效两种方案根据需求选择

方案一(蓝图的跨域直接使用CORS库即可)

from flask_cors import CORS app = Flask(__name__) CORS(app, supports_credentials=True) if __name__ == "__main__": app.run()

方案二(restful的跨域使用中间件请求后处理头信息)

from flask import make_response app = Flask(__name__) @app.after_request def restful_cros(reshead): resp = make_response(reshead) # 项目所需的其他头信息此处都可以添加 resp.headers['Access-Control-Allow-Origin'] = '*' resp.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE' resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type' return reshead if __name__ == "__main__": app.run()

 

 

最新回复(0)