使用jQuery和Tornado进行跨源资源共享(CORS)

kra*_*eki 19 javascript jquery tornado cross-domain cors

假设我有一个Tornado Web服务器(localhost)和一个网页(othermachine.com),后者包含需要对Tornado服务器进行跨域ajax调用的javascript.

所以我设置了我的龙卷风:

class BaseHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
        self.set_header("Access-Control-Allow-Headers",
            "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, X-Requested-By, If-Modified-Since, X-File-Name, Cache-Control")
Run Code Online (Sandbox Code Playgroud)

我的javascript调用jQuery:

$.ajax({
    type: 'GET',
    url: "http://localhost:8899/load/space",
    data: { src: "dH8b" },
    success: function(resp){
        console.log("ajax response: "+resp);
    },
    dataType: 'json',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader('Content-Type', 'text/plain');
        xhr.setRequestHeader('Access-Control-Request-Method', 'GET');
        xhr.setRequestHeader('Access-Control-Request-Headers', 'X-Requested-With');
        xhr.withCredentials = true;
    }
});
Run Code Online (Sandbox Code Playgroud)

但我得到了可爱的XMLHttpRequest cannot load http://localhost:8899/load/space?src=dH8b. Origin http://www.othermachine.com is not allowed by Access-Control-Allow-Origin错误.我无法分辨jQuery/Tornado(或两者兼而有之?)的哪一方面我没有正确设置.

根据开发工具,这些是jQuery请求发送的头文件:

请求标题

Accept:*/*
Origin:http://www.othermachine.com
Referer:http://www.othermachine.com/athletes.html?src=BCYQ&msgid=6xjb
User-Agent:Mozilla/5.0 ...
Run Code Online (Sandbox Code Playgroud)

如果我只是从浏览器的url字段发出请求,我会得到一个"200 OK":

响应标题

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, User-Agent, X-Requested-With, X-Requested-By, Cache-Control
Access-Control-Allow-Methods:GET,POST
Access-Control-Allow-Origin:http://www.othermachine.com
Content-Length:0
Content-Type:text/html; charset=UTF-8
Server:TornadoServer/2.2.1
Run Code Online (Sandbox Code Playgroud)

这是否意味着龙卷风正在发挥作用?我试图遵循所有stackoverflow CORS + jQuery帖子(例如这个)的建议,但无济于事.CORS在概念上看起来很简单,但也许我从根本上误解了在CORS交易中应该发生的事情......请帮忙!提前致谢.

kra*_*eki 18

没关系,编码太晚太长会导致人们错过错别字的事情.为了记录,这就是jQuery所需要的:

var data = { msgid: "dH8b" },
    url = "http://localhost:8899/load" + '?' + $.param(data);
$.getJSON( url, function(resp){
    console.log("ajax response: "+resp+" json="+JSON.stringify(resp));
});
Run Code Online (Sandbox Code Playgroud)

这就是龙卷风所需要的:

class BaseHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Access-Control-Allow-Origin", "http://www.othermachine.com")
Run Code Online (Sandbox Code Playgroud)

使用jQuery 1.7.2,Tornado 2.2.1.