19

たとえば、Tornado Web サーバー (localhost) と Web ページ (othermachine.com) があり、後者には Tornado サーバーへのクロスドメイン ajax 呼び出しを行う必要がある JavaScript が含まれているとします。

そこで、Tornado を次のように設定しました。

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")

そして、私の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;
    }
});

しかし、素敵な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 ...

単純にブラウザの 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

それは竜巻がその仕事をしていることを意味しますか? すべてのスタックオーバーフロー CORS+jQuery の投稿 (例: this ) のアドバイスに従おうとしましたが、役に立ちませんでした。CORS の概念は単純に思えますが、CORS トランザクションで何が起こるのかを根本的に誤解している可能性があります...助けてください! 前もって感謝します。

4

2 に答える 2

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));
});

そして、これがトルネードに必要なすべてです:

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

jQuery 1.7.2、Tornado2.2.1を使用します。

于 2012-07-13T13:16:52.053 に答える
-1

原点を次のように設定してみてください: othermachine.com. ウェブサイトのアドレスではなく、ドメイン名である必要があります

于 2012-07-13T05:17:10.863 に答える