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

标签 javascript html node.js server client

我从 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

服务器:

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

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/

相关文章:

javascript - 如何使 Internet Explorer 模拟指针事件 :none?

java - 在 javascript 中使用 richfaces 迭代列表中的项目

html - CSS 媒体查询 http 请求

javascript - 没有断点jquery代码无法工作

javascript - 如何动态地将对象添加到对象内部的对象

javascript - 带有用户输入和验证的垂直条形图

javascript - 无法摆脱 this.tech.isReady is null or not an object

javascript - 在从 Node 到 Java 的调用中强制执行 utf8 编码

css - Jade - 调用页面特定的 css 页面

node.js - 静态文件express/react的相对路径