当前位置: 首页 > 面试题库 >

Javascript-所请求的资源上没有“ Access-Control-Allow-Origin”标头

甄飞飙
2023-03-14
问题内容

我需要通过XmlHttpRequestJavaScript 将数据发送到Python服务器。因为我使用的是localhost,所以我需要使用CORS。我正在使用Flask框架及其模块flask_cors

作为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代码:

@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”标头。因此,不允许访问原始“空”。

我该如何解决?我知道我需要使用一些“ Access-Control-Allow-Origin”标头,但我不知道如何在此代码中实现它。顺便说一句,我需要使用纯JavaScript。


问题答案:

我使Javascript与Flask一起使用,并在可接受的方法列表中添加了“ OPTIONS”。装饰器应在路线装饰器下方使用,如下所示:

@app.route('/login', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def login()
    ...

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

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


 类似资料:
  • 问题内容: 我想访问来自同一域但端口号不同的信息,为此,我添加了响应头。 Servlet代码:( 显示在www.example.com:PORT_NUMBER上) jQuery代码:( 显示在www.example.com上) 几次我收到此错误(在控制台中): 该错误通常在执行时首次发生。第二次允许。 我的问题是代码中或代码中缺少什么? 任何建议将不胜感激。 更新1 我变了: 至: 然后我在控制台

  • 问题 我设法从我的应用程序进入keycloak登录页面。使用“我的登录详细信息”登录后,出现错误: -localhost/:1 CORS策略阻止了从源“http://localhost:4200”访问“https://localhost:8080/auth/realms/pwe-realm/protocol/openid-connect/token”的XMLHttpRequest:请求的资源上没有

  • 问题内容: 我已经创建了两个Web应用程序-客户端和服务应用程序。 当客户端和服务应用程序部署在同一Tomcat实例中时,它们之间的交互就很好。 但是,当将应用程序部署到单独的Tomcat实例(不同的计算机)中时,请求发送服务应用程序时出现以下错误。 我的客户端应用程序使用JQuery,HTML5和Bootstrap。 如下所示进行AJAX呼叫服务: 我的服务应用程序使用Spring MVC,Sp

  • 使用ProceedingError:} 我的CORS配置如下所示,我尝试了几种方法,但没有成功。 有人知道哪里不对劲吗?我看了5-6个类似的帖子,但似乎没有人能够解决问题。

  • 我已经使用Python EVE框架编写了一个API。当试图从AngularJS应用程序访问API时,它显示了如下所示的错误: 有什么问题吗

  • 我有一个运行在服务器上的API,还有一个连接到它的前端客户端来检索数据。我对跨域问题做了一些研究,并使其工作。然而,我不确定有什么改变。我现在在控制台中收到这个错误: 谢谢你