使用 Flask 解决跨域资源共享

Solve Cross Origin Resource Sharing with Flask(使用 Flask 解决跨域资源共享)
本文介绍了使用 Flask 解决跨域资源共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For the following ajax post request for Flask (how can I use data posted from ajax in 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 );
    }   
});

我得到一个 跨域资源共享 (CORS) 错误:

I get a Cross Origin Resource Sharing (CORS) error:

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.

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

I tried solving it in the two following ways, but none seems to work.

  1. 使用 Flask-CORS

这是一个用于处理 CORSFlask 扩展,它应该使跨域 AJAX 成为可能.

This is a Flask extension for handling CORS that should make cross-origin AJAX possible.

  • http://flask-cors.readthedocs.org/en/latest/
  • 如何在flask和heroku中启用CORS
  • Flask-cors 包装器不工作时应用了 jwt 身份验证包装器.
  • Javascript - 无访问权限"-Control-Allow-Origin' 标头出现在请求的资源上

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

My pythonServer.py using this solution:

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 在它所装饰的函数上.

This is an official Flask code snippet defining a decorator that should allow CORS on the functions it decorates.

  • http://flask.pocoo.org/snippets/56/
  • Python Flask 跨站 HTTPPOST - 不适用于特定的允许来源
  • http://chopapp.com/#351l7gc3

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

My pythonServer.py using this solution:

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()

您能否说明原因?

推荐答案

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

It worked like a champ, after bit modification to your code

# 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.因为正如我在许多博客和帖子中看到的那样,您应该允许特定域的访问

I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain

这篇关于使用 Flask 解决跨域资源共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)