免责声明:我是 node.js 的新手,所以我认为这个问题有一个非常基本的答案。
我在 Windows 上使用 node.js,使用 http 模块生成静态页面,内容从 js 文件生成。
服务器文件(server.js):
var http = require('http');
var fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8080);
});
HTML 文件 (index.html):
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<p id="p1">This is a static paragraph.</p>
</div>
<p>
<script type="text/javascript" src="start.js"></script>
</p>
</body>
</html>
JS文件(start.js)
var para = document.createElement("p");
var node = document.createTextNode("This text is loaded from a js file.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
当我直接加载 index.html 时,我得到以下输出:
This is a static paragraph.
This text is loaded from a js file.
^^ 这是我想要的输出。
问题:但是,当我使用node.js 并运行server.js 时,start.js 内容未加载。我得到:
This is a static paragraph.
如有任何帮助,我们将不胜感激。
仅供引用,我的文件夹结构
/
- node_modules
-- http
-- fs
- index.html
- server.js
- start.js
最佳答案
您为文件获取的每个请求 url 都需要由 Node 服务器处理。我建议使用 Express.js,因为这样可以轻松处理不同的 url 路径,并且可以直接提供文件。但是,如果您想要一个基于纯 node.js 的实现,请检查以下代码。
要从服务器提供文件,您必须将 server.js 修改为如下内容:
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
if(request.url=='/'){
fs.readFile('./index.html', function (err, html) {
if (err) {
res.send(500,{error: err});
}
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
});
} else if(request.url=='/start.js'){
fs.readFile('./start.js', function (err, jsFile) {
if (err) {
res.send(500,{error: err});
}
response.writeHeader(200, {"Content-Type": "text/javascript"});
response.write(jsFile);
response.end();
});
}
}).listen(8080);
希望这有帮助:)
关于javascript 未加载到 HTML 文件中 - nodejs + http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52584811/