瓶子Py:为jQuery AJAX请求启用CORS

2024-04-26 00:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个基于Bottle web框架的web服务的RESTful API,希望通过jQuery AJAX调用访问资源。

使用REST客户机,资源接口按预期工作,并正确处理GET、POST、。。。请求。但是当发送jQuery AJAX POST请求时,生成的OPTIONS preflight请求被简单地拒绝为“405:Method not allowed”。

我试着在瓶子服务器上启用CORS-如下所述:http://bottlepy.org/docs/dev/recipes.html#using-the-hooks-plugin 但选项请求从不调用after_request hook。

以下是我的服务器摘录:

from bottle import Bottle, run, request, response
import simplejson as json

app = Bottle()

@app.hook('after_request')
def enable_cors():
    print "after_request hook"
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

@app.post('/cors')
def lvambience():
    response.headers['Content-Type'] = 'application/json'
    return "[1]"

[...]

jQuery AJAX调用:

$.ajax({
    type: "POST",
    url: "http://192.168.169.9:8080/cors",
    data: JSON.stringify( data ),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        alert(data);
    },
    failure: function(err) {
        alert(err);
    }
});

服务器只记录405错误:

192.168.169.3 - - [23/Jun/2013 17:10:53] "OPTIONS /cors HTTP/1.1" 405 741

$.post确实可以工作,但是不能发送PUT请求将破坏RESTful服务的目的。 那么,我如何才能允许处理OPTIONS preflight请求呢?


Tags: 服务器jsonappbottledataresponserequestajax
3条回答

安装处理程序而不是挂钩。

在过去,我有两种互补的方法:decorator或瓶子插件。我给你们看,你们可以决定其中一个(或两个)是否适合你们的需要。在这两种情况下,一般的想法是:处理程序在将响应发送回客户端之前截取响应,插入CORS头,然后继续返回响应。

方法1:按路径安装(Decorator)

当您只想在某些路由上运行处理程序时,此方法更可取。只需装饰你想要它执行的每一条路线。下面是一个例子:

import bottle
from bottle import response

# the decorator
def enable_cors(fn):
    def _enable_cors(*args, **kwargs):
        # set CORS headers
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

        if bottle.request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)

    return _enable_cors


app = bottle.app()

@app.route('/cors', method=['OPTIONS', 'GET'])
@enable_cors
def lvambience():
    response.headers['Content-type'] = 'application/json'
    return '[1]'

app.run(port=8001)

方法2:全局安装(瓶子插件)

如果希望处理程序在所有或大部分路由上执行,则最好使用此方法。你只需要define a Bottle plugin一次,瓶子就会在每条路线上自动为你调用它;不需要在每条路线上指定一个装饰器。(请注意,您可以使用路由的skip参数来避免每个路由使用此处理程序。)下面是与上面的示例相对应的示例:

import bottle
from bottle import response

class EnableCors(object):
    name = 'enable_cors'
    api = 2

    def apply(self, fn, context):
        def _enable_cors(*args, **kwargs):
            # set CORS headers
            response.headers['Access-Control-Allow-Origin'] = '*'
            response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
            response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

            if bottle.request.method != 'OPTIONS':
                # actual request; reply with the actual response
                return fn(*args, **kwargs)

        return _enable_cors


app = bottle.app()

@app.route('/cors', method=['OPTIONS', 'GET'])
def lvambience():
    response.headers['Content-type'] = 'application/json'
    return '[1]'

app.install(EnableCors())

app.run(port=8001)

考虑让你的网络服务器,而不是瓶子,设置标题。

不确定这是否适用于您的情况,但在过去的项目中,我已经通过在Apache中为我的Bottle应用程序设置CORS头来解决了这个问题。它易于配置,使我的Python代码保持整洁,而且效率很高。

信息是可用的from many sources,但是如果您使用的是Apache,下面是我的配置(或多或少):

<Location "/cors">
    Header set Access-Control-Allow-Headers "Origin, Content-Type"
    Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Request-Headers "Origin, Content-Type"
</Location>

下面是对@ron.rothman的方法2的一个小改进,该方法用于全局安装CORS处理程序。他的方法要求您指定在您声明的每个路由上都接受OPTIONS方法。此解决方案为所有OPTIONS请求安装全局处理程序。

@bottle.route('/<:re:.*>', method='OPTIONS')
def enable_cors_generic_route():
    """
    This route takes priority over all others. So any request with an OPTIONS
    method will be handled by this function.

    See: https://github.com/bottlepy/bottle/issues/402

    NOTE: This means we won't 404 any invalid path that is an OPTIONS request.
    """
    add_cors_headers()

@bottle.hook('after_request')
def enable_cors_after_request_hook():
    """
    This executes after every route. We use it to attach CORS headers when
    applicable.
    """
    add_cors_headers()

def add_cors_headers():
    if SOME_CONDITION:  # You don't have to gate this
        bottle.response.headers['Access-Control-Allow-Origin'] = '*'
        bottle.response.headers['Access-Control-Allow-Methods'] = \
            'GET, POST, PUT, OPTIONS'
        bottle.response.headers['Access-Control-Allow-Headers'] = \
            'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

```

相关问题 更多 >