<legend id='1Jhe4'><style id='1Jhe4'><dir id='1Jhe4'><q id='1Jhe4'></q></dir></style></legend>
  • <tfoot id='1Jhe4'></tfoot>

        <bdo id='1Jhe4'></bdo><ul id='1Jhe4'></ul>

      <small id='1Jhe4'></small><noframes id='1Jhe4'>

      1. <i id='1Jhe4'><tr id='1Jhe4'><dt id='1Jhe4'><q id='1Jhe4'><span id='1Jhe4'><b id='1Jhe4'><form id='1Jhe4'><ins id='1Jhe4'></ins><ul id='1Jhe4'></ul><sub id='1Jhe4'></sub></form><legend id='1Jhe4'></legend><bdo id='1Jhe4'><pre id='1Jhe4'><center id='1Jhe4'></center></pre></bdo></b><th id='1Jhe4'></th></span></q></dt></tr></i><div id='1Jhe4'><tfoot id='1Jhe4'></tfoot><dl id='1Jhe4'><fieldset id='1Jhe4'></fieldset></dl></div>

        使用 Flask 解决跨域资源共享

        时间:2023-09-03
        <tfoot id='qqOrR'></tfoot>

        • <i id='qqOrR'><tr id='qqOrR'><dt id='qqOrR'><q id='qqOrR'><span id='qqOrR'><b id='qqOrR'><form id='qqOrR'><ins id='qqOrR'></ins><ul id='qqOrR'></ul><sub id='qqOrR'></sub></form><legend id='qqOrR'></legend><bdo id='qqOrR'><pre id='qqOrR'><center id='qqOrR'></center></pre></bdo></b><th id='qqOrR'></th></span></q></dt></tr></i><div id='qqOrR'><tfoot id='qqOrR'></tfoot><dl id='qqOrR'><fieldset id='qqOrR'></fieldset></dl></div>
            <tbody id='qqOrR'></tbody>
        • <small id='qqOrR'></small><noframes id='qqOrR'>

          <legend id='qqOrR'><style id='qqOrR'><dir id='qqOrR'><q id='qqOrR'></q></dir></style></legend>

              • <bdo id='qqOrR'></bdo><ul id='qqOrR'></ul>

                • 本文介绍了使用 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 解决跨域资源共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                  上一篇:CORS 请求在 Safari 中不起作用 下一篇:Microsoft Online Auth 没有“Access-Control-Allow-Origin&qu

                  相关文章

                  最新文章

                  <tfoot id='491p1'></tfoot>
                    • <bdo id='491p1'></bdo><ul id='491p1'></ul>

                  1. <i id='491p1'><tr id='491p1'><dt id='491p1'><q id='491p1'><span id='491p1'><b id='491p1'><form id='491p1'><ins id='491p1'></ins><ul id='491p1'></ul><sub id='491p1'></sub></form><legend id='491p1'></legend><bdo id='491p1'><pre id='491p1'><center id='491p1'></center></pre></bdo></b><th id='491p1'></th></span></q></dt></tr></i><div id='491p1'><tfoot id='491p1'></tfoot><dl id='491p1'><fieldset id='491p1'></fieldset></dl></div>

                    <small id='491p1'></small><noframes id='491p1'>

                    <legend id='491p1'><style id='491p1'><dir id='491p1'><q id='491p1'></q></dir></style></legend>