lan*_*cif 10 javascript node.js
我是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".
我应该怎么做?
Sam*_*uel 20
Alxandr是对的.我会尽力澄清他的答案.
碰巧你必须为你的请求写一个"路由器".下面是一个让它工作的简单方法.如果您期待www.nodebeginner.org,您将找到一种构建正确路由器的方法.
var fs = require("fs");
var http = require("http");
var url = require("url");
http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
response.writeHead(200);
if(pathname == "/") {
html = fs.readFileSync("index.html", "utf8");
response.write(html);
} else if (pathname == "/script.js") {
script = fs.readFileSync("script.js", "utf8");
response.write(script);
}
response.end();
}).listen(8888);
console.log("Listening to server on 8888...");
Run Code Online (Sandbox Code Playgroud)
问题是你的浏览器请求的是什么,你返回"index.html".因此,浏览器加载您的页面并获取HTML.该html包含您的脚本标记,浏览器会向节点请求脚本文件.但是,您的处理程序设置为忽略请求的内容,因此它只会再次返回html.
| 归档时间: |
|
| 查看次数: |
29117 次 |
| 最近记录: |