python设置跨域的最简单方法,python前后端分离允许跨域访问的方法,No 'Access-Control-Allow-Origin' header is present

版权声明:本文为作者原创文章,转载请附上原文出处链接和本声明。
本文链接:http://doc.shulijp.com/jdetail/1583814997709

对python接口发起请求浏览器出错:

Access to XMLHttpRequest at 'http://localhost:8084/swapface' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

第一种解决方法:

from functools import wraps
from flask import make_response


def allow_cross_domain(fun):
    @wraps(fun)
    def wrapper_fun(*args, **kwargs):
        rst = make_response(fun(*args, **kwargs))
        rst.headers['Access-Control-Allow-Origin'] = '*'
        rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
        allow_headers = "Referer,Accept,Origin,User-Agent"
        rst.headers['Access-Control-Allow-Headers'] = allow_headers
        return rst
    return wrapper_fun



@app.route('/hosts/')
@allow_cross_domain
def domains():
    pass

第二种解决方法:

这也是我用的比较简单的方法,引用一个库文件Flask-CORS。http://flask-cors.readthedocs.io/en/latest/具体可以参考官方文档,可以直接用pip安装。 

下面是我的引用方法

#!/usr/bin/python
# -*- coding: utf-8 -*-

from flask import Flask, request, make_response, redirect
import json,os,sys
from flask_cors import CORS, cross_origin #导入包
app = Flask(__name__)
app.debug = True
CORS(app, supports_credentials=True)#设置参数

 

还能输入1000个字符