0

Trying to implement the simplest server-client on my PC.

The argv part is because I'm debugging it in VS and it started as an application. It works as a standalone app and I want to make it a server. If I enter

http://localhost:8080/ 

in the browser I can see in the node.exe window that the server runs properly. But when I run the html with the script nothing happens (I get no response, although no error either, and the server doesn't get the request)

If anyone could help I would appreciate it.

Client:

<html>
<body>

<script type = "text/javascript">
<!-- 
    //Browser Support Code
    function ajaxFunction() {
        var ajaxRequest;  // The variable that makes Ajax possible!

        try {
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer Browsers
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
            }   
            }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function () {
            if (ajaxRequest.readyState == 4) {
                document.myForm.response.value = ajaxRequest.responseText;
            }
        }
        ajaxRequest.open("GET", "http://localhost:8080", true);
        ajaxRequest.send(null);
    }

    //-->
</script>



<form name='myForm'>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</form>
</body>
</html>

Server:

var fs       = require("fs"),
    my_http = require("http"),
    sys = require("sys");

my_http.createServer(function(request,response){  


    fs.readFile(process.argv[2], 'utf8', function(err, data) {
    if (err) {
        console.log("FILE READ ERROR: ", err);
        process.exit();
     }
    response.writeHeader(200, {"Content-Type": "text/plain"});  
    response.write("message");
    response.end();
});




}).listen(8080);  
sys.puts("Server Running on 8080");

EDIT:

Well, I made some progress you could say, but I don't like not knowing what the problem is. I created a new TypeScript project in VS and put my ajaxFunction in it and the button\textbox as in the initial html file. Now the server does get the request but it doesn't seem to call the callback function onreadystatechange.

The new client code:

default.htm:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="app.js"></script>
</head>
<body>
    <h1>TypeScript HTML App</h1>

    <div id="content"></div>
    <button onclick="ajaxFunction()">request</button> <br />
    <input type='text' name='response' />
</body>
</html>

app.ts: (it's in js though)

var response;

function ajaxFunction() {
    var ajaxRequest;  // The variable that makes Ajax possible!
    var response;

    try {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function () {
        if (ajaxRequest.readyState == 4) {
            response.innerHTML = "hi";

        }
    }
    ajaxRequest.open("GET", "http://localhost:8080", true);
    ajaxRequest.send(null);
}


window.onload = () => {
    response = document.getElementById('content');
};

I am now getting a "Cancelled" network request in Chrome's dev tools.

Mosho
  • 7,099
  • 3
  • 34
  • 51
  • Seems like you're leaving off a lot of your server code. Can you paste the whole thing so we know what's truly missing or there that we cant see – Deryck Jan 30 '14 at 23:41
  • Actually that's it, pretty much, I've added the nodejs require statements. – Mosho Jan 30 '14 at 23:49
  • did your code reduction change the outcome at all – Deryck Jan 30 '14 at 23:56
  • Nope :( I just removed some of the unneeded context, I've already tried that and many other potential fixes before I posted on SO. – Mosho Jan 31 '14 at 00:04
  • You know if you open up that `default.htm` from your desktop and try to AJAX to a server like...`http://localhost:8080`...you aren't allowed to do that. – Deryck Jan 31 '14 at 01:01
  • Then how do I get it to work? – Mosho Jan 31 '14 at 02:06
  • You run the default.htm file from the server itself. When you point your browser to `http://localhost:8080` have your node.js load default.htm. You don't need to use AJAX to load a file from Node. – Deryck Jan 31 '14 at 02:32
  • And how do I do that? – Mosho Jan 31 '14 at 06:09
  • Well I'm going to sleep for now but I'll be on 24/7 this weekend. Go to my profile for my e-mail and let me know when you're available so we can go over it in detail (unless someone here beats me to it ;) ) – Deryck Jan 31 '14 at 06:28

1 Answers1

0

New answer:

What do you get if you log some values out in your onreadystatechange handler?

ajaxRequest.onreadystatechange = function () {
    
    console.log('ajaxRequest.readyState=', ajaxRequest.readyState, ajaxRequest.status);
    
    if (ajaxRequest.readyState == 4) {
        document.myForm.response.value = ajaxRequest.responseText;
    }
}

Original answer:

There are a couple of possibilities that might be occurring.

Your ajaxRequest variable is local to the ajaxFunction() and might be getting garbage collected after the function is executed.

Try moving the ajaxRequest outside ajaxFunction() like this:

var ajaxRequest;  // The variable that makes Ajax possible!

function ajaxFunction() {
    ... rest of your client code.
}

That way the variable will still be in scope after the function has been invoked.

Alternatively, you might be running into a cross-domain security issue if your client is running on a different domain to your server (e.g. http://localhost:8081/ vs http://localhost:8080/).

Can you check if the browser is actually making the request (i.e. check with the browser's development tools and not on the server)? There should be a 'network' tab in the development tools for whichever browser you are using.

Have a look at the documentation for CORS (Cross-Origin Resource Sharing) to get an idea of what might be happening.

Edit: Here's a nice overview of cross-domain security errors and how to address it in a standard Node.js server: http://bannockburn.io/2013/09/cross-origin-resource-sharing-cors-with-a-node-js-express-js-and-sencha-touch-app/

This answer shows how to add the headers in a Connect server: How can I add CORS-Headers to a static connect server?

Community
  • 1
  • 1
Sly_cardinal
  • 12,270
  • 5
  • 49
  • 50
  • Taking ajaxRequest out of the function didn't work. In Chrome's Dev tools > network I'm getting {Method: "GET", Status(Text): "304 Not Modified", Type: "text/html", Initiator: "Other", Size(Content): "338B (1.0KB)", Time(Latency): "6ms (5ms)"} – Mosho Jan 31 '14 at 00:16
  • I'm getting the following when I just load the page and not use VS: {Method: "GET", Status(Text): "Success", Type: "text/html", Initiator: "Other", Size(Content): "0 (1.0KB)", Time(Latency): "1ms (1ms)"} – Mosho Jan 31 '14 at 00:22
  • Do you see a new request show up in the Dev Tools when you press the button? Can you log out a message/value in the `onreadystatechange` function so you know when it is running? – Sly_cardinal Jan 31 '14 at 00:25
  • Well, every time I click the button the one I mentioned above is reloaded, but I guess it's just the page itself. There is nothing else when I click the button. – Mosho Jan 31 '14 at 00:36
  • Oh, I didn't see the form in your markup. For now just try this to prevent submitting the form: `` – Sly_cardinal Jan 31 '14 at 00:46
  • Well, I made some progress you could say, but I don't like not knowing what the problem is. I created a new TypeScript project in VS and put my ajaxFunction in it and the button\textbox as in the initial html file. Now the server does get the request but it doesn't seem to call the callback function onreadystatechange. – Mosho Jan 31 '14 at 00:47
  • Does that mean that you're getting a response from the server now? – Sly_cardinal Jan 31 '14 at 00:48
  • Yes, my server is generating its output on the server side and assigns it to response, but nothing I do in the callback gets done. I'm adding the new code. – Mosho Jan 31 '14 at 00:50