如何在 node.js 的客户端包含 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17722407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to include javascript on client side of node.js?
提问by lancif
I'm a beginner of node.js and javascript.
我是 node.js 和 javascript 的初学者。
I want to include external javascript file in html code. Here is the html code, "index.html":
我想在 html 代码中包含外部 javascript 文件。这是 html 代码,“index.html”:
<script src="simple.js"></script>
And, here is the javascript code, "simple.js":
而且,这里是 javascript 代码,“simple.js”:
document.write('Hello');
When I open the "index.html" directly on a web browser(e.g. Google Chrome), It works. ("Hello" message should be displayed on the screen.)
当我直接在网络浏览器(例如 Google Chrome)上打开“index.html”时,它可以工作。(“你好”消息应该显示在屏幕上。)
However, when I tried to open the "index.html" via node.js http server, It doesn't work. Here is the node.js file, "app.js":
但是,当我尝试通过 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" and "app.js" are on same directory.) I started the http server. (by "bash$node app.js") After then, I tried to connect "localhost:8000". But, "Hello" message doesn't appear.
(“index.html”、“simple.js”和“app.js”在同一目录中。)我启动了http服务器。(通过“bash$node app.js”)之后,我尝试连接“localhost:8000”。但是,“您好”消息不会出现。
I think the "index.html" failed to include the "simple.js" on the http server.
我认为“index.html”未能在 http 服务器上包含“simple.js”。
How should I do?
我应该怎么做?
采纳答案by Alxandr
The problem is that nomatter what your browser requests, you return "index.html". So the browser loads your page and get's html. That html includes your script tag, and the browser goes asking node for the script-file. However, your handler is set up to ignore what the request is for, so it just returns the html once more.
问题是无论您的浏览器请求什么,您都会返回“index.html”。所以浏览器加载你的页面并获取 html。该 html 包含您的脚本标记,浏览器会向节点询问脚本文件。但是,您的处理程序设置为忽略请求的目的,因此它只会再次返回 html。
回答by Samuel
Alxandr is right. I will try to clarify more his answer.
亚历山大是对的。我会尽量澄清他的回答。
It happens that you have to write a "router" for your requests. Below it is a simple way to get it working. If you look forward www.nodebeginner.orgyou will find a way of build a proper router.
碰巧您必须为您的请求编写一个“路由器”。下面是一个让它工作的简单方法。如果您期待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...");
回答by Alxandr
Here is a working code. There should be more cleaner simpler code, but this is very close to minimal.
这是一个工作代码。应该有更简洁的代码,但这非常接近最小。
This code suppose your index.html and other files are under /client dir.
此代码假设您的 index.html 和其他文件位于 /client 目录下。
Good luck.
祝你好运。
var fs = require('fs');
var url = require("url");
var path = require('path');
var mime = require('mime');
var log = console.log;
var handler = function (req, res)
{
var dir = "/client";
var uri = url.parse(req.url).pathname;
if (uri == "/")
{
uri = "index.html";
}
var filename = path.join(dir, uri);
log(filename);
log(mime.lookup(filename));
fs.readFile(__dirname + filename,
function (err, data)
{
if (err)
{
res.writeHead(500);
return res.end('Error loading index.html');
}
log(data);
log(filename + " has read");
res.setHeader('content-type', mime.lookup(filename));
res.writeHead(200);
res.end(data);
});
}
回答by Quentin
Your handler is hardcoded to always return the content of /index.html. You need to pay attention to the resource that is being requested and return the right one. (i.e. if the browser asks for simple.jsthen you need to give it simple.jsinstead of index.html).
您的处理程序被硬编码为始终返回/index.html. 您需要注意正在请求的资源并返回正确的资源。(即,如果浏览器要求,simple.js那么您需要提供它simple.js而不是index.html)。
回答by zloctb
function contentType(ext) {
var ct;
switch (ext) {
case '.html':
ct = 'text/html';
break;
case '.css':
ct = 'text/css';
break;
case '.js':
ct = 'text/javascript';
break;
default:
ct = 'text/plain';
break;
}
return {'Content-Type': ct};
}
var PATH = 'C:/Users/DELL P26E/node_modules'
var http = require("http");
var fs = require('fs');
var url = require("url");
var path = require("path")
var fileName = "D:/index.html";
var server = http.createServer (function (request, response) {
var dir = "D:/";
var uri = url.parse(request.url).pathname;
if (uri == "/")
{
uri = "index.html";
}
var filename = path.join(dir, uri);
fs.readFile( filename,
function (err, data)
{
console.log(err)
if (err)
{
response.writeHead(500);
return response.end('Error loading index.html');
}
var ext = path.extname(filename)
response.setHeader('content-type',contentType(ext));
response.writeHead(200);
response.end(data);
});
}).listen(3000);
console.log('Server running on 8124') ;

