标题可能会很困惑,所以我会用我的代码来解释 这是我的 Nodejs 服务器(“server.js”)代码:
var http = require('http');
var fs = require('fs');
var fserver = function (req, res) {
fs.readFile('hieu.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
};
http.createServer(fserver).listen(8080);
这是我的 hieu.html 文件:
<html>
<body>
<script src="check.js">
</script>
<p> a line </p>
<script>
var table = document.createElement("table");
for (var i = 0; i < 10; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 10; j++) {
var td = document.createElement("BUTTON");
if(i%2 == j%2) td.appendChild(document.createTextNode("B"));
else td.appendChild(document.createTextNode("W"));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
</script>
<p> hieudzvkl </p>
</body>
</html>
我的 check.js 文件只是一行代码,将数字 5 写入文档。
如果我只是运行 hieu.html 文件,我将得到:
然而,如果我运行 ("server.js") 代码,我将得到:
如您所见,脚本 src ="check.js"
没有出现在 res 中。
我不明白为什么会这样。有什么办法可以解决这个问题吗? 提前致谢!
最佳答案
当您从 nodeJS 检索 html 文件时,浏览器指向网络服务器上的一个位置(在本例中,它似乎托管在端口 8080 上)。 html 文件引用的任何其他资源也将从该位置获取,除非它们是绝对 URL。所以这里发生的是你的浏览器试图从与 html 文件相同的位置获取 check.js
,换句话说,从网络服务器。您必须更新您的 nodeJS 代码,以便它了解如何为 hieu.html
文件和 check.js
文件提供服务。
考虑在您的 server.js
代码中添加类似于以下内容的逻辑:
var http = require('http');
var fs = require('fs');
var fserver = function (req, res) {
if (req.url === '/check.js') {
// Insert Code here, such as...
fs.readFile('check.js', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(data);
res.end();
});
} else {
fs.readFile('hieu.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
};
http.createServer(fserver).listen(8080);
关于javascript - 如何在用作nodejs服务器响应的html文件中包含外部脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48752401/