flask中的跨域处理-方法二不使用第三方库

方法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)
相关推荐
知行合一。。。1 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y2 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
lifewange2 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
GreenTea2 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
pluvium272 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
2401_827499993 小时前
python项目实战09-AI智能伴侣(ai_partner_5-6)
开发语言·python
PD我是你的真爱粉3 小时前
MCP 协议详解:从架构、工作流到 Python 技术栈落地
开发语言·python·架构
ZhengEnCi3 小时前
P2G-Python字符串方法完全指南-split、join、strip、replace的Python编程利器
python
是小蟹呀^3 小时前
【总结】LangChain中工具的使用
python·langchain·agent·tool
宝贝儿好3 小时前
【LLM】第二章:文本表示:词袋模型、小案例:基于文本的推荐系统(酒店推荐)
人工智能·python·深度学习·神经网络·自然语言处理·机器人·语音识别