2016-05-14 43 views
0

我有一個在nodejs中使用Express開發的http服務器。 服務器在端口3000本地運行。CORS仍然處於SecurityError狀態:操作不安全

有一個html頁面(index.html),它調用ajax GET內容(作爲html內容類型)。 這些ajax內容也在同一個端口上的相同服務器上提供,位於相同的http protocole中。

在節點服務器應用程序中,我添加了Cors Same Origin標頭,但是index.html在控制檯中仍然存在錯誤:「安全錯誤:操作不安全」。

在瀏覽器控制檯,我看到成功的頭約「訪問控制允許來源」節點快速應用,等等

此外,相同的應用也爲另一位頁面, index.html可以成功獲取沒有任何安全錯誤的數據。

您有任何其他建議嗎?

function getData(url, type, CType, id) { 
    //var xhr = new XMLHttpRequest(); 
    //xhr.open(type, url, true); 
    //xhr.withCredentials = true; 
    //xhr.onload = function() { 
    //console.log(xhr.responseText); 
    //if(CType == 'text/html') { $(id).append(xhr.responseText); } 
    //}; 
    //xhr.send(); 

$.ajax({ 
    url: url, 
    type: type, 
    crossDomain:true, 
    cors:true, 
    success: function(data){ 
    $(id).append(data); 
    }, 
    error: function(data) { 
    console.log('ERROR '+url); 
    console.log(data); 
    $(id).append(getError(url)); 
    } 
}); 


getData(location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '')+'/modules/mymodule', 'text/html', 'GET', '#content'); 
+0

看起來這兩個請求都是HTTP或HTTPS(不是混合)。是這樣嗎?是否有任何重定向? (其實,它看起來像你正在向*相同的*起源請求,爲什麼你只是使用相對URL?) – Quentin

+0

你在測試什麼瀏覽器?如果你嘗試不同的瀏覽器,你會得到一個不同的(也許更有啓發性的)錯誤信息? – Quentin

+0

>你爲什麼只使用相對URL? 嗡嗡聲..這是一個很好的問題..並沒有理由... 剛剛在相對測試:getData('/ modules/mymodule','text/html','GET','#content'); 和我有相同的結果。 –

回答

0

initially tested with Firefox 44.0.2 and Chromium 48.0.2564.82 gives: "SyntaxError: Failed to execute 'open' on 'XMLHttpRequest': 'TEXT/HTML' is not a valid HTTP method."

你有你的中間兩個參數倒退。

getData(location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '')+'/modules/mymodule', 'text/html', 'GET', '#content'); 

第二個參數應該是"GET"和第三個參數"text/html"

+1

ohhhh ....親愛的...我感覺如此.....愚蠢...... –

-1

嘗試增加在Ajax調用這三個參數從客戶端向服務器

crossDomain:true, 
    cors:true, 
    contentType:"application/json;charset=utf-8", 

主編之一:

$.ajax({ 
    url: url, 
    type: type, 
    method:"GET", 
    crossDomain:true, 
    cors:true, 
    contentType:"application/html;charset=utf-8" 
    success: function(data){ 
    $(id).append(data); 
    }, 
    error: function(data) { 
    console.log('ERROR '+url); 
    console.log(data); 
    $(id).append(getError(url)); 
    } 
}); 

此外,如果你沒有得到這種方法正確試試這個:

Add Header in AJAX Request with jQuery

+0

不幸的是它以相同的錯誤結束。 –

+0

'crossDomain:true,'會導致jQuery將通常添加到XHR請求中的自定義HTTP標頭抑制到同一個來源,以防將HTTP重定向到其他來源。如果這是問題,那麼錯誤就是抱怨Access-Control-Allow-Headers標題。 – Quentin

+0

'cors:true,'不是ajax函數支持的選項。它會被忽略。 – Quentin

相關問題