方法1(第三方库)
pip install flask-cors
python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": ["http://localhost:63342", "http://localhost:63345"]}})
方法2(声明周期函数)
python
from flask import Flask, jsonify, request, make_response
# 创建Flask应用程序实例
app = Flask(__name__)
origins = ["http://localhost:63342", "http://localhost:63345"]
# 定义路由和视图函数
@app.route('/api/object', methods=["get", "post"])
def hello_world():
loginWay = request.args.get("loginWay")
username = ""
if loginWay == "sms":
mobile = request.json.get("mobile")
code = request.json.get("code")
if mobile != "153" or code != "123":
return jsonify(code=-1, msg="短信验证码错误或已过期")
elif loginWay == "password":
username = request.json.get("username")
password = request.json.get("password")
if username != "myn" or password != "149":
return jsonify(code=-1, msg="用户名或密码错误")
data = {"account": username if username else mobile, "loginWay": loginWay, "msg": "登录成功"}
return jsonify(code=0, msg="登录成功", data=data)
@app.after_request
def app_after_request(response):
current_origin = request.headers.get("Origin")
response.headers['Access-Control-Allow-Origin'] = current_origin
return response
@app.before_request
def app_before_request():
if request.method == "OPTIONS" and request.headers.get("Origin") in origins:
resp = make_response()
resp.headers.add('Access-Control-Allow-Credentials', 'true')
resp.headers.add('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
resp.headers.add('Access-Control-Allow-Headers',
"Content-Type,X-Requested-With,X-Csrf-Token,DNT,X-CustomHeader,"
"Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Authorization")
return resp
# 启动应用程序
if __name__ == '__main__':
app.run(debug=True)