[英]Node.js return a JS file locally
Inside my html file, I am using this: 在我的html文件中,我正在使用以下代码:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
However, I was not allowed to connect to internet during the running. 但是,跑步期间我不允许连接到互联网。 How can I use node js to return this file locally. 如何使用node js在本地返回此文件。 I already download this file "jquery.min.js" in my local machine. 我已经在本地计算机上下载了该文件“ jquery.min.js”。
I am trying to use this code, but it does not work. 我正在尝试使用此代码,但是它不起作用。
function callback(data) {
res.writeHead(200, {"Content-Type": "text/html"});
var str = data+"";
res.write(str);
res.end();
}
HTMLtemplate.load("jquery.min.js", callback);
You can't easily serve up both the web page and jquery in a simple node server that looks like this: 您无法轻松地在如下所示的简单节点服务器中同时提供网页和jquery:
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
server.listen(8000);
I think you are going to need some router or framework to serve up multiple http endpoints and static assets. 我认为您将需要一些路由器或框架来服务多个http端点和静态资产。 Many people use express: 很多人使用快递:
http://expressjs.com/ http://expressjs.com/
Or even something as simple as this: 甚至像这样简单的事情:
https://github.com/creationix/node-router https://github.com/creationix/node-router
I suppose you could serve up a web page with jquery embedded in it using a naked node server by doing something like this (this is only psuedo-code): 我想您可以通过执行以下操作来使用裸节点服务器为其中嵌入了jquery的网页提供服务(这只是伪代码):
var http = require('http');
var fs = require('fs');
var html = "<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>REPLACEME</script>
</head>
<body>
</body>
</html>";
var server = http.createServer(function (request, response) {
fs.readFile('jquery.js', 'utf8', function (err,data) {
response.writeHead(200, {"Content-Type": "text/html"});
response.end(html.replace('REPLACEME', data));
});
});
server.listen(8000);
But that seems very wrong except, perhaps, as an exercise that demonstrates what a web framework does. 但这似乎是非常错误的,除了可能是作为演示Web框架功能的练习。 Unless you are doing this for school, just install one of the above frameworks (or some other) and it will be easy. 除非您在学校这样做,否则只需安装上述框架之一(或其他框架),这将很容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.