简体   繁体   中英

Node Server and Apache Server - No 'Access-Control-Allow-Origin' Error

I have a JS script running that sends and attempts to receive JSON data.

This JS Script is running on WAMP and the other server is running as a Node server. (Node server is on localhost:3000).

When attempting to send/receive data, an error is thrown in the console:

XMLHttpRequest cannot load http://localhost:3000/ ?... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost ' is therefore not allowed access.

My Javascript code:

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();
}

Node Server:

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}`);
})

Could someone explain to me why this is occurring and how the given fix works?

Thanks!

This is probably a good place to look -> "No 'Access-Control-Allow-Origin' header is present on the requested resource"

Take note of answer #2 and the google chrome CORS extension. I've been using it a lot recently and it def comes in handy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM