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

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

客户端.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 onResRdy 中的异常:TypeError:无法读取未定义的属性“htmlRes”


localhost/:1 Unchecked runtime.lastError: 无法建立连接。接收端不存在。


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


www说
浏览 312回答 1
1回答

RISEBY

浏览器(因为你有<script src="/client.js">)请求/client.js服务器:获取请求运行&nbsp;response读取&nbsp;index.html发送到浏览器由于index.html以 开头<,浏览器在尝试将其作为 JavaScript 运行时会抛出错误。你为什么在浏览器index.html要求时给它client.js?您需要检查请求对象,确定请求的 URL,编写逻辑以返回具有正确状态代码和正确内容类型的正确资源,然后将其返回给客户端。该Node.js的文档中有这样一个例子,但你或许应该停止尝试使用createServer直接-因为它涉及到车轮再造一个巨大的量-切换到使用快递,并通过(很短)工作入门指南,其中包括上一节使用static模块来提供静态文件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript