瓶潘岳:启用CORS的jQuery AJAX请求 [英] Bottle Py: Enabling CORS for jQuery AJAX requests

查看:606
本文介绍了瓶潘岳:启用CORS的jQuery AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的瓶子上的Web框架的Web服务的REST的API,并希望访问的资源使用jQuery AJAX调用。

I'm working on a RESTful API of a web service on the Bottle Web Framework and want to access the resources with jQuery AJAX calls.

使用REST客户端,资源接口工作打算,并妥善处理GET,POST,...请求。但发送一个jQuery AJAX POST请求时,所产生的选项preflight请求被拒绝简单的。405:不允许的方法

Using a REST client, the resource interfaces work as intended and properly handle GET, POST, ... requests. But when sending a jQuery AJAX POST request, the resulting OPTIONS preflight request is simply denied as '405: Method not allowed'.

我试图在瓶服务器上启用CORS - 如下所述:<一href="http://bottlepy.org/docs/dev/recipes.html#using-the-hooks-plugin">http://bottlepy.org/docs/dev/recipes.html#using-the-hooks-plugin 但在 after_request挂钩永远不会被调用的OPTIONS请求。

I tried to enable CORS on the Bottle server - as described here: http://bottlepy.org/docs/dev/recipes.html#using-the-hooks-plugin But the after_request hook is never called for the OPTIONS request.

下面是我的服务器的摘录:

Here is an excerpt of my server:

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调用:

The jQuery AJAX call:

$.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错误:

The server only logs a 405 error:

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

$。后做的工作,但是不能够发送PUT请求将击败RESTful服务的宗旨。 所以,我怎么能允许处理的选项preflight要求?

$.post does work, but not being able to send PUT requests would defeat the purpose of a RESTful service. So how can I allow the OPTIONS preflight request to be handled?

推荐答案

安装的处理程序,而不是一个钩。

Install a handler instead of a hook.

有两种互补的方法,我已经在过去做到了这一点:装饰,或瓶插件。我会告诉你俩,你可以决定是否其中一个(或两个),满足您的需求。在这两种情况下,一般的想法是:一个处理程序截取该响应之前,它的发回给客户机,嵌入式CORS标头,然后进到返回响应

There are two complementary ways I've done this in the past: decorator, or Bottle plugin. I'll show you both and you can decide whether one (or both) of them suit your needs. In both cases, the general idea is: a handler intercepts the response before it's sent back to the client, inserts the CORS headers, and then proceeds to return the response.

此方法是preferable当您只需要运行一些你的路由的处理程序。只是装点您希望它执行的每个路由。这里有一个例子:

This method is preferable when you only want to run the handler on some of your routes. Just decorate each route that you want it to execute on. Here's an example:

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:安装在全球范围内(瓶插件)

此方法是preferable,如果你想在处理程序上的所有或大部分的路线运行。您只需定义瓶插件一次,瓶子会在每次航线上自动调用它给你;不需要指定的每一个装饰器。 (请注意,您可以使用路由的参数,以避免这种情况的处理程序上的每个路由)。下面是对应于上面的那个例子:

Method 2: Install Globally (Bottle Plugin)

This method is preferable if you want the handler to execute on all or most of your routes. You'll just define a Bottle plugin once, and Bottle will automatically call it for you on every route; no need to specify a decorator on each one. (Note that you can use a route's skip parameter to avoid this handler on a per-route basis.) Here's an example that corresponds to the one above:

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)

这篇关于瓶潘岳:启用CORS的jQuery AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆