美文网首页
解决No 'Access-Control-Allow-O

解决No 'Access-Control-Allow-O

作者: MccReeee | 来源:发表于2017-05-26 15:36 被阅读2215次
image.png image.png

用python的Flask写的服务器,web用jquery的ajax请求时候报这个错。
官方文档给的说明在这里http://flask.pocoo.org/snippets/56/

简单点说就是在启动app的地方加上一个装饰器@crossdomain(origin='*')

from flask import Flask
app = Flask(__name__)

@app.route("/")
@crossdomain(origin='*')
def hello():
    return "Hello World!"

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

具体的装饰器实现代码也要复制进去

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


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,POST,PUT,DELETE'
            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

完整代码如下

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


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



from flask import Flask
app = Flask(__name__)

@app.route("/")
@crossdomain(origin='*')
def hello():
    return "Hello World!"

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

上述方法虽然可行,但是不够完善,经昊宇大神点播,采用以下办法更合适

# -*- coding:utf-8 -*-
from flask import Flask, request
import json


def after_request(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
    return response


def create_app():
    app = Flask(__name__)
    app.after_request(after_request)

相关文章

  • 解决No 'Access-Control-Allow-O

    用python的Flask写的服务器,web用jquery的ajax请求时候报这个错。官方文档给的说明在这里htt...

  • 解决UnicodeEncodeError: 'ascii

    最近写的爬虫在运行中,抛出了以下异常 看异常情况应该是编码问题。 解决方法:在文件前加上以下几句代码即可 Pyth...

  • 解决1130 Host 'localhost'

    WAMP 64bit 安装好后,连接数据库,提示 #1130 Host 'localhost' is not al...

  • 解决 SVN Skipped 'xxx' --

    svn revert --depth=infinity /www/xcg.cgsoft.net/themes/si...

  • Java常见面试题汇总-----------Java多线程(多线

    39、Synchronized的底层原理   synchronized是JAVA中解决并发编程中最常用的方法。  ...

  • matplotlib不显示中文问题

    参考解决方法 https://www.jianshu.com/p/b02ec7dc39dd

  • 遇到打包错误

    错误提示 警告 错误提示 解决方式:利用ant重新打包 http://bbs.csdn.net/topics/39...

  • 2019-08-26

    冯萍焦点解决中十四学员坚持分享164天 读书坚持58天 《建构解决之道》39页、《父母效能训练》205页---21...

  • 2019-08-27

    冯萍焦点解决中十四学员坚持分享165天 读书坚持59天 《建构解决之道》39页、《父母效能训练》205页---21...

  • 2019-08-26

    冯萍焦点解决中十四学员坚持分享163天 读书坚持57天 《建构解决之道》39页、《父母效能训练》199页---20...

网友评论

      本文标题:解决No 'Access-Control-Allow-O

      本文链接:https://www.haomeiwen.com/subject/ixrxfxtx.html