python flask 跨域问题 解决方案


import urllib.parse
from flask_cors import CORS
from flask import Flask, request, make_response,  session

def config_after_handler(app):

    CORS(app, suppors_credentials=True, resources={r'/*'})

    @app.before_request
    def bf_request():
        if request.path not in ["/user/login", "/user/logout"]:
            token = session.get("token")
            if not token:
                pass

    @app.after_request
    def at_request(resp):      # 解决跨域问题
        referrer = request.referrer
        parse = urllib.parse

        scheme = parse.urlsplit(referrer).scheme
        netloc = parse.urlsplit(referrer).netloc

        resp = make_response(resp)
        resp.headers['Access-Control-Allow-Credentials'] = 'true'
        resp.headers['Access-Control-Allow-Origin'] = "{scheme}://{netloc}".format(scheme=scheme, netloc=netloc)
        resp.headers['Access-Control-Allow-Methods'] = 'GET,POST,OPTIONS'
        resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type,x-token'
        return resp


你可能感兴趣的:(python)