我是node.js和javascript的初学者.
我想在html代码中包含外部javascript文件.这是html代码,"index.html":
<script src="simple.js"></script>
Run Code Online (Sandbox Code Playgroud)
而且,这是javascript代码,"simple.js":
document.write('Hello');
Run Code Online (Sandbox Code Playgroud)
当我直接在网络浏览器(例如谷歌浏览器)上打开"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);
});
}
Run Code Online (Sandbox Code Playgroud)
("index.html","simple.js"和"app.js"在同一目录中.)我启动了http服务器.(通过"bash $ node app.js")之后,我尝试连接"localhost:8000".但是,"Hello"消息不会出现.
我认为"index.html"未能在http服务器上包含"simple.js".
我应该怎么做?
我是一个完整的node.js新手和苦苦挣扎的基础.我有一个html文件,我想在本地主机环境中使用node.js在html页面中调用外部javascript文件.
JS:
var http = require('http'),
fs = require('fs');
fs.readFile('HtmlPage.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(8000);});
Run Code Online (Sandbox Code Playgroud)
HTML:
<script type="text/javascript" >
function validation() {
alert("Hai");
var fs = require("JavaScript1.js");
}
</script>
Run Code Online (Sandbox Code Playgroud)