使用 Node.js 作为简单的 Web 服务器

新手上路,请多包涵

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

如何提供包含一些图像、CSS 和 JavaScript 的单个 HTML 页面?

原文由 idophir 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 510
1 个回答

创建一个简单的 Node.js Web 服务器并从文件异步提供 HTML 页面

创建我的第一个 node.js 服务器后,我找到了一种简单有效的方法。

我们可以在开始时加载一次,而不是为每个请求加载 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

原文由 Okiemute Gold 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题