我从 Node.js 开始,我的第一个程序已经遇到了问题。下面是我正在使用的代码。索引.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;
});
服务器.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
服务器:
- 获取请求
- 运行
response
- 读取
index.html
- 将其发送到浏览器
自 index.html
以 <
开头,当浏览器尝试将其作为 JavaScript 运行时会抛出错误。
为什么你给浏览器index.html
当它询问client.js
时?
您需要检查请求对象,确定所请求的 URL,编写逻辑以返回具有正确状态代码和正确内容类型的正确资源,然后将其返回到客户端。
Node.js documentation has an example of this但您可能应该停止尝试使用 createServer
直接 - 因为它涉及大量的轮子改造 - 切换到使用 Express并完成(非常短)getting started guide其中包括有关使用 static
的部分提供静态文件的模块。
关于javascript - 链接index.html client.js 和 server.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704000/