我想运行一个非常简单的HTTP服务器。对example.com的每个GET请求都应该得到index.html,但作为一个常规的HTML页面(即,与阅读普通网页时的体验相同)。
使用下面的代码,我可以读取index.html的内容。我如何服务index.html作为一个普通的网页?
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(index);
}).listen(9615);
下面的一个建议很复杂,需要我为我想使用的每个资源(CSS、JavaScript、图像)文件写一个get行。
我如何能提供一个单一的HTML页面与一些图像,CSS和JavaScript?
创建一个简单的Node.js Web服务器,并从一个文件异步服务一个HTML页面
创建我的第一个node.js服务器时,我找到了一个简单而有效的方法来做到这一点。
我们可以在开始时加载一次HTML,而不是为每个请求加载HTML。然后返回我们在启动时加载的数据。
const host = "localhost";
const port = 5000;
const http = require("HTTP");
const fs = require("fs").promises;
let htmlFile;
const reqListenerFunc = function (req, resp) {
resp.setHeader("Content-Type", "text/html");
resp.writeHead(200);
resp.end(htmlFile);
};
const simpleServer = http.createServer(reqListenerFunc);
// // Using Arrow function directly
// const simpleServer = http.createServer( (req, resp) => {
// resp.setHeader("Content-Type", "text/html");
// resp.writeHead(200);
// resp.end(htmlFile);
// });
fs.readFile(__dirname + "/index.html")
.then(content => {
htmlFile = content;
simpleServer.listen(port, host, () => {
console.log(`Node.js web server is running on http://${host}:${port}`);
});
})
.catch(err => {
console.error(`Cannot read index.html file. <br> Error: ${err}`);
process.exit(1);
});
阅读更多信息:https://www.digitalocean.com/community/tutorials/how-to-create-a-web-server-in-node-js-with-the-http-module
Express函数sendFile正是你所需要的,因为你想从节点的web服务器功能,Express是自然的选择,然后服务静态文件变得简单:
res.sendFile('/path_to_your/index.html')
更多信息请点击:https://expressjs.com/en/api.html#res.sendFile
一个用express web server for node的小例子:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
运行这个,并导航到http://localhost:8080
在此基础上,允许你提供css和图像等静态文件,下面是另一个例子:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/css'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
所以创建一个名为css的子文件夹,把你的静态内容放在里面,它将被你的index.html用于方便引用,比如:
<link type="text/css" rel="stylesheet" href="/css/style.css" />
注意href中的相对路径!
拖鞋!
最快捷的方法:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/../public')); // ← adjust
app.listen(3000, function() { console.log('listening'); });
你的方法:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
console.dir(req.url);
// will get you '/' or 'index.html' or 'css/styles.css' ...
// • you need to isolate extension
// • have a small mimetype lookup array/object
// • only there and then reading the file
// • delivering it after setting the right content type
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('ok');
}).listen(3001);
这里有很多复杂的答案。如果你不打算处理nodeJS文件/数据库,只是想提供静态html/css/js/图像,就像你的问题建议的那样,然后简单地安装pushstate-server模块或类似的;
这是一个“一行程序”,它将创建并启动一个迷你网站。只需将整个块粘贴到终端中相应的目录中。
mkdir mysite; \
cd mysite; \
npm install pushstate-server --save; \
mkdir app; \
touch app/index.html; \
echo '<h1>Hello World</h1>' > app/index.html; \
touch server.js; \
echo "var server = require('pushstate-server');server.start({ port: 3000, directory: './app' });" > server.js; \
node server.js
打开浏览器,访问http://localhost:3000。完成了。
服务器将使用应用程序目录作为根目录来提供文件。要添加额外的资产,只需将它们放在该目录中。