用 Flask 解决跨域资源共享

IT技术 javascript python ajax flask cors
2021-02-03 05:53:55

对于以下ajax发布请求Flask如何使用从 ajax 在flask 中发布的数据?):

$.ajax({
    url: "http://127.0.0.1:5000/foo", 
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({'inputVar': 1}),
    success: function( data ) { 
        alert( "success" + data );
    }   
});

我收到一个Cross Origin Resource Sharing (CORS)错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'null' is therefore not allowed access. 
The response had HTTP status code 500.

我尝试通过以下两种方式解决它,但似乎都不起作用。

  1. 使用 Flask-CORS

这是一个Flask处理扩展CORS,应该使跨域 AJAX 成为可能。

我的pythonServer.py使用这个解决方案:

from flask import Flask
from flask.ext.cors import CORS, cross_origin

app = Flask(__name__)
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route('/foo', methods=['POST','OPTIONS'])
@cross_origin(origin='*',headers=['Content-Type','Authorization'])
def foo():
    return request.json['inputVar']

if __name__ == '__main__':
    app.run()
  1. 使用特定的 Flask 装饰器

这是一个官方的Flask 代码片段,定义了一个装饰器,它应该允许CORS它装饰的函数。

我的pythonServer.py使用这个解决方案:

from flask import Flask, make_response, request, current_app
from datetime import timedelta
from functools import update_wrapper

app = Flask(__name__)

def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

@app.route('/foo', methods=['GET','POST','OPTIONS'])
@crossdomain(origin="*")
def foo():
    return request.json['inputVar']

if __name__ == '__main__':
    app.run()

你能给出一些说明为什么会这样吗?

6个回答

您可以通过简单的方式获得结果:

@app.route('your route', methods=['GET'])
def yourMethod(params):
    response = flask.jsonify({'some': 'data'})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
最好添加跨域实现!
2021-03-18 05:53:55
@Salvador Dali - 如果我正在渲染模板而不仅仅是 json 对象,您知道什么是允许交叉原点的正确方法吗?即最后一行代码yourMethod是:return render_template('template.html',some_var = response)
2021-03-27 05:53:55
简单有效
2021-03-28 05:53:55
杰出的!我同意,简单而有效。IMO 应该被接受的答案
2021-03-28 05:53:55
这可以用在 post 方法中吗?我尝试了一种文件上传方法,但失败了。
2021-03-28 05:53:55

好吧,我遇到了同样的问题。对于可能登陆此页面的新用户。只需按照他们的官方文档进行操作即可。

安装 Flask-cors

pip install -U flask-cors

然后在应用程序初始化后,flask-cors使用默认参数进行初始化

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
   return "Hello, cross-origin-world!"
也适用于我 Tks!
2021-03-15 05:53:55
如何设置Access-Control-Max-Ageflask_cors
2021-03-17 05:53:55
这给了我以下错误 Access to XMLHttpRequest at 'my_domain' from origin ' 127.0.0.1:5000 ' has been Blocked by CORS policy: Response to preflight request does not pass access control check: The 'Access-Control-Allow- Origin' 标头包含多个值 ' 127.0.0.1:5000 , *',但只允许一个。
2021-03-18 05:53:55
2021-03-20 05:53:55
为我工作!!谢谢你。这应该是公认的答案!
2021-03-26 05:53:55

在对您的代码进行一些修改后,它就像一个冠军

# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy   dog'
app.config['CORS_HEADERS'] = 'Content-Type'

cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})

@app.route('/foo', methods=['POST'])
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def foo():
    return request.json['inputVar']

if __name__ == '__main__':
   app.run()

我用 localhost 替换了 *。正如我在许多博客和帖子中所读到的那样,您应该允许访问特定域

另请参阅下面的单行:stackoverflow.com/a/46637194/3559330
2021-04-04 05:53:55
如果有人使用蓝图,您需要将 CORS() 添加到每个蓝图,例如: my_blueprint = Blueprint('my_bp_name', name , url_prefix="/my-prefix") CORS(my_blueprint)
2021-04-12 05:53:55

不妨把这个作为一个答案。我今天遇到了同样的问题,它比预期的更不是问题。添加 CORS 功能后,您必须重新启动 Flask 服务器(ctrl + c->python manage.py runserver或您使用的任何方法))以使更改生效,即使代码正确也是如此。否则 CORS 将无法在活动实例中工作。

这是对我来说的样子和它的工作原理(Python 3.6.1,Flask 0.12):

工厂.py

from flask import Flask
from flask_cors import CORS  # This is the magic


def create_app(register_stuffs=True):
    """Configure the app and views"""
    app = Flask(__name__)
    CORS(app)  # This makes the CORS feature cover all routes in the app

    if register_stuffs:
        register_views(app)
    return app


def register_views(app):
    """Setup the base routes for various features."""
    from backend.apps.api.views import ApiView
    ApiView.register(app, route_base="/api/v1.0/")

视图.py

from flask import jsonify
from flask_classy import FlaskView, route


class ApiView(FlaskView):
    @route("/", methods=["GET"])
    def index(self):
        return "API v1.0"

    @route("/stuff", methods=["GET", "POST"])
    def news(self):
        return jsonify({
            "stuff": "Here be stuff"
        })

在我的 React 应用程序 console.log 中:

Sending request:
GET /stuff
With parameters:
null
bundle.js:17316 Received data from Api:
{"stuff": "Here be stuff"}

请注意,Access-Control-Allow-Origin在许多情况下(例如这种情况)在 Flask 响应对象中设置标头是没问题的,但在提供静态资产时(至少在生产设置中)则无效。这是因为静态资产直接由前端 Web 服务器(通常是 Nginx 或 Apache)提供服务。因此,在这种情况下,您必须在 Web 服务器级别设置响应标头,而不是在 Flask 中。

有关更多详细信息,请参阅我不久前写的这篇文章,其中解释了如何设置标题(在我的例子中,我试图对 Font Awesome 资产进行跨域服务)。

此外,正如@Satu 所说,在 JS AJAX 请求的情况下,您可能只需要允许访问特定域。对于请求静态资产(如字体文件),我认为规则不那么严格,并且更容易接受允许访问任何域。