节点服务器和Apache服务器 - 没有'访问控制 - 允许 - 来源'错误

时间:2017-06-01 21:47:34

标签: javascript node.js xmlhttprequest cross-domain

我有一个运行的JS脚本,它发送并尝试接收JSON数据。

此JS脚本在WAMP上运行,另一台服务器作为Node服务器运行。 (节点服务器在localhost:3000上)。

尝试发送/接收数据时,控制台中会抛出错误:

  

XMLHttpRequest无法加载http://localhost:3000/?...对预检请求的响应没有通过访问控制检查:否' Access-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}`);
})

有人可以向我解释为什么会发生这种情况以及给定修复的工作原理吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

这可能是个好看的地方 - > "No 'Access-Control-Allow-Origin' header is present on the requested resource"

记下答案#2和Google Chrome CORS扩展程序。我最近一直在使用它并且def派上用场了。