【Flask】解决跨域CORS

from flask import Flask, request, jsonify, make_response
from flask_cors import CORS, cross_origin
from dataCities import cities

app = Flask(__name__)
CORS(app, supports_credentials=True)


@app.route("/v1/cities", methods=["GET", 'OPTIONS'])
def hello():
    get_city_type = request.args.get('type')
    #print(get_city_type)
    # print(cities)
    if get_city_type == 'guess':
        data = cities[1]
    if get_city_type == 'hot':
        data = cities[2]
    if get_city_type == 'group':
        data = cities[1]
    #print(data)
    #print(type(data))
    return jsonify(data), 201, {'Content-Type': 'application/json'}


@app.after_request
def af_request(resp):
    """
    #请求钩子,在所有的请求发生后执行,加入headers。
    :param resp:
    :return:
    """
    resp = make_response(resp)
    resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080'
    resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
    resp.headers['Access-Control-Allow-Credentials'] = 'true'
    resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return resp

猜你喜欢

转载自www.cnblogs.com/colipso/p/12130184.html