Link index.html client.js and server.js

随声附和 提交于 2019-12-31 05:49:07

问题


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?


回答1:


The browser 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.

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.



来源:https://stackoverflow.com/questions/57572302/link-index-html-client-js-and-server-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!