这会很长:
好的,我正在开发一个 google 日历小工具,它向托管在 Google App Engine 上的 Python webapp2 REST api 发送请求。
当我尝试发布由于 CORS 而不允许我发布的内容时,问题就来了。 在 Chromes 的 DevTools 中它说:
Method: OPTIONS.
Status: (failed) Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
Origin https://hq34i4geprnp5vci191ljfuhcoerscl4-a-calendar-opensocial.googleusercontent.com is not allowed by Access-Control-Allow-Origin.
我知道这是因为 CORS。这里:
Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin'
它说我必须添加
Access-Control-Allow-Origin: *
到 header ,但话又说回来,我是 ajax 的新手,我想知道它是否以这种方式完成:
$.ajax({
type: "POST",
url: "https://myapp.appspot.com/service",
contentType: "application/json; charset=utf-8",
data: data,
beforeSend: function (request)
{
request.setRequestHeader("Access-Control-Allow-Origin", "*");
}
success: function(data) {
alert("AJAX done");
}
});
添加此 header 后输出不同(这让我怀疑来源是否被允许,虽然我真的不知道):
Method: OPTIONS.
Status: (failed) Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
XMLHttpRequest cannot load https://myapp.appspot.com/service. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers.
我什至发现了这个:
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
这让我可以执行 GET 请求,但我想了解如何在没有它的情况下执行这些请求。
我的网络服务器上还有这个:
...
class webService(webapp2.RequestHandler):
options(self):
self.response.write('options')
post(self):
self.response.write('post')
application = webapp2.WSGIApplication([
('/', MainPage),
('/service', webService)
], debug=True)
我不知道是否必须向网络服务器添加更多内容,也没有找到说明我必须这样做的信息。 此外,我认为我已接近实现 CORS 请求,但我找不到解释这一切的示例。
请帮忙。
最佳答案
好的,我修好了。
首先我意识到here header 是由服务器发送的,所以我在 AJAX 请求中发送这些 header 时做错了。
最后,在搜索全局网络后,我找到了我所缺少的东西。这是愚蠢的事情。我找到了修复所有问题的页面:
http://enable-cors.org/server_appengine.html
所以最后一切看起来像这样:
$.ajax({
type: "POST",
url: "https://myapp.appspot.com/service",
contentType: "application/json; charset=utf-8",
data: data,
success: function(data) {
alert("AJAX done");
}
});
在网络服务中:
class webService(webapp2.RequestHandler):
def get(self):
self.response.headers.add_header('Access-Control-Allow-Origin', '*')
self.response.headers['Content-Type'] = 'application/json'
# do something
def post(self):
self.response.headers.add_header('Access-Control-Allow-Origin', '*')
self.response.headers['Content-Type'] = 'application/json'
# do something
def options(self):
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE'
关于python - CORS - 使用 AJAX 在 Python (webapp2) 网络服务上发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18760224/