Search code examples
javascripthtmlnode.jsserverclient

Link index.html client.js and server.js


I'm starting with Node.js and I have already a problem in my first program. Below is the code I'm using. Index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Random Temperatures</title>
  </head>
  <body>
    <input type="text" id="tb" name="tb" />
    <input type="button" value="Random Number!" id="myButton" name="myButton"/>
    <script src="client.js"></script>
</body>
</html>

Client.js:

const textBox = document.getElementById('tb');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
    var rnd = Math.floor(Math.random() * 100);
    textBox.value = rnd;
});

Server.js:

var app = require('http').createServer(response);
var fs = require('fs');
app.listen(8080);
console.log("App running…");
function response(req, res) {
    fs.readFile(__dirname + '/public/index.html',
    function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Failed to load file index.html');
        }
        res.writeHead(200);
        res.end(data);
    });
}

When I start the application I go to the browser the text box and the button appear. But in the browser console I'm getting these errors:

client.js:1 Uncaught SyntaxError: Unexpected token <

ContentScript.js:112 Exception in onResRdy: TypeError: Cannot read property 'htmlRes' of undefined

localhost/:1 Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

I guess my problem is the linking between the 3 files but I tried several things and I can't solve the problem. I'm sure it's a stupid error but forgive me I'm just getting start. Any advice?


Solution

  • The browser (because you have <script src="/client.js">) makes a request for /client.js

    The server:

    1. Gets the request
    2. Runs response
    3. Reads index.html
    4. Sends it to the browser

    Since index.html starts with <, the browser throws an error when it tries to run it as JavaScript.

    Why are you giving the browser index.html when it asks for client.js?

    You need to examine the request object, determine what URL is being asked for, write logic to return the correct resource with the correct status code and the correct content-type, and then return that to the client.

    The Node.js documentation has an example of this but you should probably stop trying to use createServer directly — since it involves a massive amount of wheel reinvention — switch to using Express and work through the (very short) getting started guide which includes a section on using the static module to serve up static files.