首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript -请求的资源上没有'Access-Control-Allow-Origin‘标头

Javascript -请求的资源上没有'Access-Control-Allow-Origin‘标头
EN

Stack Overflow用户
提问于 2014-03-05 03:41:16
回答 7查看 84.5K关注 0票数 56

我需要通过XmlHttpRequest将数据从JavaScript发送到Python服务器。因为我使用的是本地主机,所以我需要使用CORS。我使用的是Flask框架及其模块flask_cors

作为JavaScript,我有这样的想法:

代码语言:javascript
复制
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("POST", "http://localhost:5000/signin", true);
    var params = "email=" + email + "&password=" + password;


    xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }
    xmlhttp.send(params);

和Python代码:

代码语言:javascript
复制
@app.route('/signin', methods=['POST'])
@cross_origin()
def sign_in():
    email = cgi.escape(request.values["email"])
    password = cgi.escape(request.values["password"])

但是当我执行它的时候,我得到了这样的消息:

XMLHttpRequest无法加载localhost:5000/signin。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源'null‘。

我该怎么解决它呢?我知道我需要使用一些"Access-Control-Allow-Origin“头,但我不知道如何在这段代码中实现它。顺便说一下,我需要使用纯JavaScript。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2014-03-05 04:32:22

通过使用这个decorator,并将“选项”添加到我的可接受方法列表中,我获得了使用Flask的Javascript。装饰器应该在你的路由装饰器下面使用,如下所示:

代码语言:javascript
复制
@app.route('/login', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def login()
    ...

编辑:链接似乎已断开。这是我用过的装饰器。

代码语言:javascript
复制
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):
    """Decorator function that allows crossdomain requests.
      Courtesy of
      https://blog.skyred.fi/articles/better-crossdomain-snippet-for-flask.html
    """
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    # use str instead of basestring if using Python 3.x
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    # use str instead of basestring if using Python 3.x
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        """ Determines which methods are allowed
        """
        if methods is not None:
            return methods

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

    def decorator(f):
        """The decorator function
        """
        def wrapped_function(*args, **kwargs):
            """Caries out the actual cross domain code
            """
            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)
            h['Access-Control-Allow-Credentials'] = 'true'
            h['Access-Control-Allow-Headers'] = \
                "Origin, X-Requested-With, Content-Type, Accept, Authorization"
            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
票数 37
EN

Stack Overflow用户

发布于 2015-09-24 04:58:00

我使用过flask-cors扩展。

使用pip install flask-cors安装

那就很简单了

代码语言:javascript
复制
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

这将允许所有域

票数 90
EN

Stack Overflow用户

发布于 2017-02-17 07:13:11

老问题,但对于有这个问题的未来谷歌用户,我在我的flask-restful应用程序中解决了这个问题(以及其他一些与CORS有关的下游问题),在我的app.py文件中添加了以下内容:

代码语言:javascript
复制
app = Flask(__name__)
api = Api(app)

@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response


if __name__ == '__main__':
    app.run()
票数 55
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22181384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档