为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

www说 2021-09-17 21:00:01
我从 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 个文件之间的链接,但我尝试了几件事,但无法解决问题。我确定这是一个愚蠢的错误,但请原谅我才刚刚开始。有什么建议吗?
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

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

服务器:

  1. 获取请求

  2. 运行 response

  3. 读取 index.html

  4. 发送到浏览器

由于index.html以 开头<,浏览器在尝试将其作为 JavaScript 运行时会抛出错误。

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

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

Node.js的文档中有这样一个例子,但你或许应该停止尝试使用createServer直接-因为它涉及到车轮再造一个巨大的量-切换到使用快递,并通过(很短)工作入门指南,其中包括上一节使用static模块来提供静态文件。


查看完整回答
反对 回复 2021-09-17
  • 1 回答
  • 0 关注
  • 311 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号