我是 Node.js 和 javascript 的初学者。
我想在 html 代码中包含外部 javascript 文件。这是 html 代码“index.html”:
<script src="simple.js"></script>
并且,这里是 javascript 代码“simple.js”:
document.write('Hello');
当我直接在网络浏览器(例如 Google Chrome)上打开“index.html”时,它可以工作。
(屏幕上应显示“Hello”消息。)
但是,当我尝试通过node.js http服务器打开“index.html”时,它不起作用。
这是node.js 文件“app.js”:
var app = require('http').createServer(handler)
, fs = require('fs')
app.listen(8000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
(“index.html”、“simple.js”和“app.js”位于同一目录中。)
我启动了http服务器。 (通过“bash$node app.js”)
之后,我尝试连接“localhost:8000”。
但是,“你好”消息没有出现。
我认为“index.html”未能包含http 服务器上的“simple.js”。
我应该怎么做?