我想运行一个非常简单的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?


当前回答

对于简单的nodejs服务器,已经有一些很好的解决方案。 如果你在修改文件时需要实时重新加载,还有一个解决方案。

npm install lite-server -g

导航您的目录并执行

lite-server

它将打开浏览器为您实时重新加载。

其他回答

最简单的Node.js服务器就是:

$ npm install http-server -g

现在你可以通过以下命令运行服务器:

$ cd MyApp

$ http-server

如果你使用的是NPM 5.2.0或更新版本,你可以使用http-server而不用安装npx。不建议在生产中使用,但这是快速让服务器在本地主机上运行的好方法。

$ npx http-server

或者,你可以试试这个,打开你的网络浏览器,启用CORS请求:

$ http-server -o --cors

如需更多选项,请查看GitHub上的http-server文档,或运行:

$ http-server --help

NodeJitsu还有很多其他不错的特性和非常简单的部署。

特色餐叉

当然,您可以轻松地用自己的fork充值这些功能。你可能会发现这个项目现有的800多个分支中的一个已经完成了:

https://github.com/nodeapps/http-server/network

轻服务器:一个自动刷新的选择

一个很好的http-server替代方案是light-server。它支持文件监视和自动刷新以及许多其他功能。

$ npm install -g light-server 
$ light-server

添加到Windows资源管理器中的目录上下文菜单

 reg.exe add HKCR\Directory\shell\LightServer\command /ve /t REG_EXPAND_SZ /f /d "\"C:\nodejs\light-server.cmd\" \"-o\" \"-s\" \"%V\""

简单JSON REST服务器

如果您需要为原型项目创建一个简单的REST服务器,那么json-server可能就是您要找的。

自动刷新编辑器

大多数网页编辑器和IDE工具现在都包含一个网络服务器,它可以监视你的源文件,并在它们更改时自动刷新你的网页。

我使用Visual Studio代码Live服务器。

开源文本编辑器括号还包括一个NodeJS静态web服务器。只要打开括号中的任何HTML文件,按“实时预览”,它就会启动一个静态服务器,并在页面上打开浏览器。当您编辑和保存HTML文件时,浏览器将自动刷新。这在测试自适应网站时尤其有用。在多种浏览器/窗口大小/设备上打开HTML页面。保存您的HTML页面,并立即查看您的自适应内容是否工作,因为它们都自动刷新。

Web / SPA / PWA /移动/桌面/浏览器Ext Web开发人员

一些SPA框架包括一个内置的Webpack DevServer版本,可以检测源文件的更改,并触发SPA或PWA web应用程序的增量重建和补丁(称为热重新加载)。以下是一些流行的SPA框架可以做到这一点。

VueJS开发者

对于VueJS开发人员来说,最喜欢的是Quasar Framework,它包括了Webpack DevServer的开箱即用开关,以支持服务器端呈现(SSR)和代理规则,以解决CORS问题。它包括大量优化的组件,旨在适应移动和桌面。这些允许您为所有平台构建一个应用程序(SPA, SPA+SSR, PWA, PWA+SSR, Cordova和电容器移动AppStore应用程序,电子桌面节点+VueJS应用程序,甚至浏览器扩展)。

另一个流行的是NuxtJS,它也支持静态HTML/CSS代码生成,以及其他UI组件套件的插件的SSR或no-SSR构建模式。

React框架开发人员

ReactJS开发人员还可以设置热重载。

Cordova/电容器+离子框架开发人员

Iconic是一个仅用于移动设备的混合组件框架,现在支持VueJS、React和Angular开发。ionic工具内置了一个具有自动刷新功能的本地服务器。只需从应用程序文件夹中运行ionic serve即可。更好的是……ionic serve -lab用于查看iOS和Android的自动刷新视图。

我在npm上发现了一个有趣的库,可能对你有用。它叫做mime(npm install mime或https://github.com/broofa/node-mime),它可以确定文件的mime类型。下面是我用它写的一个web服务器的例子:

var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path  = unescape(__dirname + req.url)
var code = 200
 if(fs.existsSync(path)) {
    if(fs.lstatSync(path).isDirectory()) {
        if(fs.existsSync(path+"index.html")) {
        path += "index.html"
        } else {
            code = 403
            resp.writeHead(code, {"Content-Type": "text/plain"});
            resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
        }
    }
    resp.writeHead(code, {"Content-Type": mime.lookup(path)})
    fs.readFile(path, function (e, r) {
    resp.end(r);

})
} else {
    code = 404
    resp.writeHead(code, {"Content-Type":"text/plain"});
    resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(9000,"localhost");
console.log("Listening at http://localhost:9000")

这将服务于任何常规的文本或图像文件(.html, .css, .js, .pdf, .jpg, .png, .m4a和.mp3是我测试过的扩展名,但理论上它应该适用于所有文件)

开发人员指出

下面是我用它得到的输出示例:

Listening at http://localhost:9000
GET 200 OK /cloud
GET 404 Not Found /cloud/favicon.ico
GET 200 OK /cloud/icon.png
GET 200 OK /
GET 200 OK /501.png
GET 200 OK /cloud/manifest.json
GET 200 OK /config.log
GET 200 OK /export1.png
GET 200 OK /Chrome3DGlasses.pdf
GET 200 OK /cloud
GET 200 OK /-1
GET 200 OK /Delta-Vs_for_inner_Solar_System.svg

注意路径构造中的unescape函数。这是为了允许包含空格和编码字符的文件名。

创建一个简单的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

我使用下面的代码来启动一个简单的web服务器,如果Url中没有提到文件,它会渲染默认的html文件。

var http = require('http'),
fs = require('fs'),
url = require('url'),
rootFolder = '/views/',
defaultFileName = '/views/5 Tips on improving Programming Logic   Geek Files.htm';


http.createServer(function(req, res){

    var fileName = url.parse(req.url).pathname;
    // If no file name in Url, use default file name
    fileName = (fileName == "/") ? defaultFileName : rootFolder + fileName;

    fs.readFile(__dirname + decodeURIComponent(fileName), 'binary',function(err, content){
        if (content != null && content != '' ){
            res.writeHead(200,{'Content-Length':content.length});
            res.write(content);
        }
        res.end();
    });

}).listen(8800);

它将呈现所有的js, css和图像文件,以及所有的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': 'html'});
res.end(index);
}).listen(9615);

//Just Change The CONTENT TYPE to 'html'