Flask CORS策略阻止请求问题求助
各位大佬好,我现在卡到一个非常头疼的问题上了:我想通过CORS配置让我的Flask-Rest API接收来自网站的请求,但一直被CORS策略拦截,完全没法正常通信,求各位帮忙看看!
我的网站部署在https://example.com,而REST API是跑在https://example.com:5000的。
下面是我写的Python代码(用了Flask RestAPI):
app = Flask(__name__) app.config.from_object(ProductionConfig) CORS(app,resources={r"/*": {"origins": "*"}},supports_credentials=True) api = Api(app) @app.after_request def add_cors_headers(response): response.headers.add('Access-Control-Allow-Origin',"https://example.com") response.headers.add('Access-Control-Allow-Credentials','true') response.headers.add('Access-Control-Allow-Methods',"GET,POST,OPTIONS,HEAD") response.headers.add('Access-Control-Allow-Headers',"Origin, X-Requested-With, Content-Type, Accept, Authorization")
结果浏览器控制台一直报这个错误:
Access to fetch at 'https://example.com:5000/folders?page=1&limit=25&loader=false' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我实在搞不明白——明明我既通过CORS()初始化配置了跨域,又在after_request里手动加了Access-Control-Allow-Origin头,为什么控制台还会说“请求的资源上不存在'Access-Control-Allow-Origin'头”啊?
我现在急着把这个网站正式上线,真的需要大家的帮助,任何建议我都会非常感激!
备注:内容来源于stack exchange,提问作者Elcid_91

