我正在使用Bottle Web框架开发RESTful API的Web服务,并希望使用jQuery AJAX调用来访问资源。
使用REST客户端,资源接口按预期工作并正确处理GET、POST等请求。但是,发送jQuery AJAX POST请求时,生成的OPTIONS预检请求被简单地拒绝为“405:方法不允许”。
我尝试在Bottle服务器上启用CORS-如此处所述:http://bottlepy.org/docs/dev/recipes.html#using-the-hooks-plugin 但是对于OPTIONS请求,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预检请求呢?
if bottle.request.method!= 'OPTIONS':
替换了else:
。现在一切都很好 :) 如果您能解决这个问题,我可以将您的答案标记为解决方案! 感谢您的帮助。 - Joern