23 lines
891 B
Python
23 lines
891 B
Python
|
|
from flask import request, jsonify, make_response
|
||
|
|
from functools import wraps
|
||
|
|
|
||
|
|
def add_cors_headers(response):
|
||
|
|
"""为响应添加CORS头部"""
|
||
|
|
# 允许所有源访问(在生产环境中可以根据需要限制特定源)
|
||
|
|
response.headers['Access-Control-Allow-Origin'] = '*'
|
||
|
|
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
|
||
|
|
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
|
||
|
|
response.headers['Access-Control-Max-Age'] = '86400' # 24小时
|
||
|
|
return response
|
||
|
|
|
||
|
|
def cors_after(response):
|
||
|
|
"""在每个请求后添加CORS头部"""
|
||
|
|
return add_cors_headers(response)
|
||
|
|
|
||
|
|
def handle_preflight():
|
||
|
|
"""处理预检请求"""
|
||
|
|
if request.method == "OPTIONS":
|
||
|
|
response = make_response()
|
||
|
|
response = add_cors_headers(response)
|
||
|
|
return response
|
||
|
|
return None
|