0
我有一個JS腳本運行,發送並嘗試接收JSON數據。節點服務器和Apache服務器 - 沒有'訪問控制 - 允許來源'錯誤
此JS腳本運行在WAMP上,另一臺服務器作爲節點服務器運行。 (節點服務器在localhost:3000上)。
當試圖發送/接收數據,錯誤在控制檯拋出:
的XMLHttpRequest無法加載http://localhost:3000/ ...迴應預檢要求未通過訪問控制檢查:沒有「訪問 - Control-Allow-Origin'標題出現在請求的資源上。因此不允許訪問原產地'http://localhost'。
我的Javascript代碼:
function sendHands(){
console.log("sending hands");
var xhr = new XMLHttpRequest();
var params = getHandsFromDom();
var hand1 = params[0];
var hand2 = params[1];
var url = "http://localhost:3000/?hand1="+hand1+"&"+"hand2="+hand2;
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log("player1score: " + json.player1score);
document.getElementById("result").value = xhr.responseText;
}
};
xhr.send();
}
節點服務器:
const requestHandler = (request, response) => {
var urlParts = url.parse(request.url, true),
urlParams = urlParts.query, //JSON hand data
body = "";
// if the request is a GET request
if(request.method == 'GET'){
response.writeHead(200, {'Content-Type':'application/json'});
var body = "";
var paramData = "";
request.on('data' , function(data){
body += data;
});
process.on("uncaughtException", function(e){
console.log("An error occurred: " + e);
});
request.on("error", function(e){
console.log("Error caught!");
});
request.on('end', function(){
var hand1 = JSON.parse(urlParams.hand1),
hand2 = JSON.parse(urlParams.hand2),
hand3 = (urlParams.hand3 != null || urlParams.hand3 != undefined)
? JSON.parse(urlParams.hand3) : null,
//process settlement of given hands
hands = _assocArrayGenerator(hand1, hand2, hand3),
settlement = pa.settlement(hands),
jsonSettlement = {
player1score : settlement[0],
player2score : settlement[1],
player3score : settlement[2]
};
response.writeHead(200, {'Content-type':'application/json'});
console.log("Server accessed. Result: " + settlement);
response.end(JSON.stringify(jsonSettlement));
});
}
};
server.listen(port, (err) => {
if (err) {
return console.log('Error occured with the server: ', err);
}
console.log(`Server is listening on http://localhost:${port}`);
})
難道這是爲什麼發生和給定的修補程序的工作怎麼有人向我解釋?
謝謝!
我來看看,謝謝! :) –