flask实现跨域访问的两种方式

1,862 阅读1分钟
  1. 设置响应请求头实现跨域访问
from flask import Flask, request, jsonify, make_response
import func.manager as manager
@app.route('/login', methods=['POST'])
def login():
    # 获取client请求
    getData = request.form

    # 构建account
    account = {
        'user': getData['user'],
        'password': getData['password']
    }

    # 登陆验证
    myManager = manager.Manager()
    check = myManager.login_check(account)

    # 构建response对象
    result = {
        "stateCode": 0,
        "message": "API调用成功",
        "data": check
    }
    response = make_response(jsonify(result))
    # 设置响应请求头
    response.headers["Access-Control-Allow-Origin"] = '*'	# 允许使用响应数据的域。也可以利用请求header中的host字段做一个过滤器。
    response.headers["Access-Control-Allow-Methods"] = 'POST'	# 允许的请求方法
    response.headers["Access-Control-Allow-Headers"] = "x-requested-with,content-type"	# 允许的请求header

    return response
  1. 从flask_cors 导入CORS
from flask_cors import CORS
CORS(app)

参考:blog.csdn.net/sj1551/arti…