fhuseynli
fhuseynli

Reputation: 650

How can I get simple response from node.js server?

I am trying to learn Node.js (creating REST API and sending message from server). So I have an issue about sending response from server to client side. When I am logging the request from server side I see the request but I am not able to send message to client side.

My Node.js server:

//handle a user request
function onRequest(request, response){
    if(request.method =='GET' && request.url=='/'){
        response.writeHead(200, {"Content-Type":"text/html"});
        fs.createReadStream("./index.html").pipe(response);
        console.log(request.url);
    }
    else if(request.method =='GET' && request.url=='/try'){
     console.log("I am getting the request");
     response.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow Origin":"*"});

        response.write("test message");
        response.end();
    }
    else{
        console.log(request.url);
        send404Response(response);
    }

}

http.createServer(onRequest).listen(8888);

My client side function:

function sendRequest(){

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.onreadystatechange==4 && xhttp.status == 200) {
            alert("test alert") ;
            }
        }
        xhttp.open("GET", "http://127.0.0.1:8888/try", true);
        xhttp.send();

        }

Any help is appreciated... thanks in advance

Upvotes: 2

Views: 1158

Answers (3)

fhuseynli
fhuseynli

Reputation: 650

I solved the problem by changing the if statement from:

if (xhttp.onreadystatechange==4 && xhttp.status == 200)

To:

if (xhttp.readyState==4 && xhttp.status == 200)

Upvotes: 1

Pelit Mamani
Pelit Mamani

Reputation: 2381

Thanks for the update. You seem to have run into the notorious issue of cross domain requests... it's a security issue, roughly speaking browsers won't allow a page loaded from one site to issue ajax requests into another site.

In other words, it matters how your browser opened that html which issues the ajax request. It should be ok if the page itself was obtained , say, through 'http://127.0.0.1:8888/index.html' (where index.html has some button or whatever that issues the ajax). If your final intention is indeed to deploy the static page on the same server+port that makes the dynamic replies, you're fine. If you meant for them to be deployed on different machines/ports, you'll probably need to look into CORS...

Upvotes: 0

Pavel Durov
Pavel Durov

Reputation: 1297

Try to add 'Access-Control-Allow-Origin' to your response header:

Here is a link which explains CORS: http://www.html5rocks.com/en/tutorials/cors/

Upvotes: 0

Related Questions