Link index.html client.js 和 server.js

Link index.html client.js and server.js

我从 Node.js 开始,我的第一个程序已经有问题了。下面是我正在使用的代码。 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);
    });
}

当我启动应用程序时,我转到浏览器,文本框和按钮出现。但是在浏览器控制台中我收到了这些错误:

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.

我想我的问题是这 3 个文件之间的链接问题,但我尝试了几种方法但无法解决问题。我确定这是一个愚蠢的错误,但请原谅我,我才刚刚开始。有什么建议吗?

浏览器(因为你有<script src="/client.js">)请求/client.js

服务器:

  1. 获取请求
  2. 运行 response
  3. 阅读index.html
  4. 发送到浏览器

由于 index.html< 开头,浏览器在尝试将其 运行 作为 JavaScript.

时抛出错误

为什么当浏览器要求 client.js 时你给浏览器 index.html

您需要检查请求对象,确定 URL 请求什么,将逻辑写入 return 具有正确状态的 correct 资源代码和正确的内容类型,然后 return 发送给客户端。

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,其中包含有关使用 static 模块提供静态文件的部分。