2010-08-05 131 views
5

我在Cross Origin Resource Sharing和Prototype中遇到了一些麻煩。我有一個簡單的發佈請求到外國資源,並且對於簡單的發佈請求,有一些必須滿足的規則:跨原點資源共享原型JS

Content-Type必須位於application/x-www-form-urlencoded,multipart/form-data或text/plain,一個簡單的請求不會使用http請求設置自定義標頭,並且服務器必須將Access-Control-Allow-Origin標頭設置爲正確。

與香草JavaScript XMLHttpRequest一切正常,但與PrototypeJS它不會工作,因爲它接縫Prototype設置一些自定義標題,我不知道如何防止它。

我通過嘗試在原型:

new Ajax.Request('some.foreign-host.com/res.php', { 
    method: 'post', 
    postBody: 'foo=bar', 
    contentType: 'application/x-www-form-urlencoded', 
    onSuccess: function(e){ 
    // some custom code 
    } 
}); 

不知道如何拿到的樣機送這樣一個簡單的CORS請求?


我有一個簡單的的JavaScript的XMLHttpRequest創建的頭的轉儲:

POST /bthesis/returnJSON.php HTTP/1.1  
Host: foreign-host.com       
Connection: keep-alive     
Referer: this-host.com 
Content-Length: 9       
Origin: this-host.com  
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 
Accept: */*        
User-Agent: [...] 
Accept-Encoding: gzip,deflate,sdch  
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

,並通過原型請求創建的頭:

OPTIONS /bthesis/returnJSON.php HTTP/1.1 
Host: foreign-host.com       
Connection: keep-alive     
Referer: this-host.com 
Access-Control-Request-Method: POST  
Origin: this-host.com  
Access-Control-Request-Headers: X-Prototype-Version, X-Requested-With, Content-type, Accept 
Accept: */*        
User-Agent: [...] 
Accept-Encoding: gzip,deflate,sdch  
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

原型使用一個完全不同的頭文件集......這會導致控制檯中出現以下錯誤:

XMLHttpRequest無法加載foreign-host.com/bthesis/returnJSON.php。 Access-Control-Allow-Headers不允許請求標頭字段X-Prototype-Version。 不肯不安全頭「X-JSON」

奇怪的是,在這兩種情況下,Web服務器返回所請求的資源(我看到它的「資源」 Chrome瀏覽開發者控制檯的),但它接縫該原型不能訪問它在某種程度上

回答

0

也許你可以設置原點頭自己在Ajax請求,像這樣

new Ajax.Request('some.foreign-host.com/res.php', { 
    method: 'post', 
    postBody: 'foo=bar', 
    requestHeaders: {Origin: 'http://www.my.local-host.com'} 
    contentType: 'application/x-www-form-urlencoded', 
    onSuccess: function(e){ 
     // some custom code 
    } 
}); 

從來沒有嘗試過自己,但... 與原型版本,會發生什麼?請求是否被髮出,然後什麼也沒有返回,或者是被丟棄的響應,或者是什麼?

11

我遇到同樣的問題。共享鏈接@mplungjan包含了答案:

您只需讓瀏覽器知道x-json頭是使用access-control-expose-headers

我使用Ruby的這一行on Rails的控制器安全

headers['Access-Control-Expose-Headers'] = 'x-json' 

(這應該是很容易轉換成其他編程語言:))

更多細節在這個page

+1

這爲我工作。謝謝 – FosAvance 2017-01-30 14:35:41

1

我在other SO question找到解決方案。它適用於我 - details are here

概括起來 - 你需要在你Ajax.RequestonCreate事件,消除非標頭:

onCreate: function(response) { // here comes the fix 
     var t = response.transport; 
     t.setRequestHeader = t.setRequestHeader.wrap(function(original, k, v) { 
      if (/^(accept|accept-language|content-language)$/i.test(k)) 
       return original(k, v); 
      if (/^content-type$/i.test(k) && 
       /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)(;.+)?$/i.test(v)) 
       return original(k, v); 
      return; 
     }); 
    }