小编典典

链接index.html client.js和server.js

node.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未捕获的SyntaxError:意外令牌<

ContentScript.js:112 onResRdy中的异常:TypeError:无法读取未定义的属性’htmlRes’

localhost /:1未经检查的runtime.lastError:无法建立连接。接收端不存在。

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


阅读 379

收藏
2020-07-07

共1个答案

小编典典

浏览器发出请求 /client.js

服务器:

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

由于index.html开头为<,因此浏览器尝试将其作为JavaScript运行时会引发错误。

为什么要index.html在要求时提供浏览器client.js

您需要检查请求对象,确定请求的URL,编写逻辑以使用正确的状态代码和正确的内容类型返回 正确的 资源,然后将其返回给客户端。

您可能应该停止尝试createServer直接使用-因为这涉及大量的车轮重新发明-
切换到使用Express并完成(非常简短的)入门指南,其中包括使用static模块提供静态文件的部分。

2020-07-07