[英]How to write an html page with scripts to response in node.js?
I am very new to node.js. 我对node.js非常陌生。 I am trying to write to the response an html file named
index.html
which has a reference to a javascript file test.js
: 我正在尝试向响应中写入一个名为
index.html
的html文件,该文件具有对javascript文件test.js
的引用:
<!-- Content of index.html -->
<html>
<head>
<script src="test.js"></script>
</head>
<body>
<h2>Hello</h2>
</body>
</html>
There is only one line in my test.js
我的
test.js
只有一行
console.log("asdf")
Now, to use node.js to display index.html
, I wrote the following main.js
现在,要使用node.js显示
index.html
,我编写了以下main.js
let http = require("http")
let fs = require("fs")
let hostname = "127.0.0.1"
let port = 3000
let server = http.createServer((request, response) => {
fs.readFile("./index.html", (error, html) => {
response.statusCode = 200;
response.setHeader("Content-Type", "text/html")
response.write(html)
response.end()
})
})
I entered node main.js
in the terminal, and typed http://127.0.0.1:3000/
in the browser. 我在终端中输入
node main.js
,然后在浏览器中输入http://127.0.0.1:3000/
。 The console shows an exception saying 控制台显示异常提示
Uncaught SyntaxError : Unexpected token
<
未捕获到的SyntaxError :意外令牌
<
It turns out that the browser got test.js
wrong. 事实证明,浏览器弄错了
test.js
As shown in the image below, it seems that the browser thinks text.js
contains the content of index.html
. 如下图所示,浏览器似乎认为
text.js
包含index.html
的内容。
What went wrong? 什么地方出了错?
All files mentioned are organized in the following manner: 提到的所有文件都按以下方式组织:
.
├── index.html
├── main.js
└── test.js
Your server is sending the contents of index.html
no matter what the browser is asking for. 无论浏览器要求什么,您的服务器都会发送
index.html
的内容。 Below is a verbose example of how you may want to handle requests for index.html
vs test.js
. 下面是一个详细示例,说明您可能希望如何处理对
index.html
与test.js
请求。
let server = http.createServer((request, response) => {
if(request.url === '/' || request.url === '/index.html') {
fs.readFile("./index.html", (error, html) => {
response.end(html);
});
} else if(request.url === '/test.js') {
fs.readFile("./test.js", (error, js) => {
response.end(js);
});
} else {
response.end('idk what to send u, sowie');
}
});
As you can see, some of the code repeats! 如您所见,其中一些代码会重复! You can refactor the code to say "please try to give them the exact file they're asking for; if I hit an error when reading the file, it must not exist, therefore I will send them a 404 response."
您可以将代码重构为“请尝试向他们提供他们所需要的确切文件;如果在读取文件时遇到错误,则该文件一定不存在,因此我将向他们发送404响应。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.