2016-06-23 118 views
1

我有相關的CORS一個問題,我無法擺脫著名「訪問控制允許來源」標頭出現在所請求的資源

的XMLHttpRequest不能加載外部domain.com 。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此,原產地「mydomain.com」是不允許訪問

我試了一下:

// Create the XHR object. 
function createCORSRequest(method, url) { 
    var xhr = new XMLHttpRequest(); 
    if ("withCredentials" in xhr) { 
    // XHR for Chrome/Firefox/Opera/Safari. 
    xhr.open(method, url, true); 
    } else if (typeof XDomainRequest != "undefined") { 
    // XDomainRequest for IE. 
    xhr = new XDomainRequest(); 
    xhr.open(method, url); 
    } else { 
    // CORS not supported. 
    xhr = null; 
    } 
    return xhr; 
} 

// Helper method to parse the title tag from the response. 
function getTitle(text) { 
    return text.match('<title>(.*)?</title>')[1]; 
} 

// Make the actual CORS request. 
function makeCorsRequest() { 
    // All HTML5 Rocks properties support CORS. 
    var url = 'http://updates.html5rocks.com'; 

    var xhr = createCORSRequest('GET', url); 
    if (!xhr) { 
    alert('CORS not supported'); 
    return; 
    } 

    // Response handlers. 
    xhr.onload = function() { 
    var text = xhr.responseText; 
    var title = getTitle(text); 
    alert('Response from CORS request to ' + url + ': ' + title); 
    }; 

    xhr.onerror = function() { 
    alert('Woops, there was an error making the request.'); 
    }; 

    xhr.send(); 
} 

上面的例子只是在啓動靜態HTML,當我把它上傳到我得到我上面提到的錯誤主要領域的作品。

回答

0

確保您的服務器的訪問控制允許來源設置爲* 假設可以說,它的NodeJS

//添加標題 app.use(功能(REQ,水庫,下一個){

// Website you wish to allow to connect 
res.setHeader('Access-Control-Allow-Origin', '*'); 

// Request methods you wish to allow 
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); 

// Request headers you wish to allow 
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); 

// Set to true if you need the website to include cookies in the requests sent 
// to the API (e.g. in case you use sessions) 
res.setHeader('Access-Control-Allow-Credentials', true); 

// Pass to next layer of middleware 
next(); 

});

+0

我該怎麼做? – Gintas

+0

我還挺新的。 – Gintas

+0

任何人都可以幫忙嗎? – Gintas

相關問題