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


当前回答

如果你的电脑上安装了节点,你可能有NPM,如果你不需要NodeJS的东西,你可以使用服务包来实现这个:

1 -在您的PC上安装软件包:

npm install -g serve

2 -提供静态文件夹:

serve <path> 
d:> serve d:\StaticSite

它会告诉你你的静态文件夹正在被服务的端口,只需像这样导航到主机:

http://localhost:3000

其他回答

看看这个要点。我在这里复制它以供参考,但要点已定期更新。

Node.JS静态文件web服务器。将它放在您的路径中以启动任何目录中的服务器,需要一个可选的端口参数。

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

更新

gist确实处理css和js文件。我自己也用过。在“二进制”模式下使用读/写不是问题。这仅仅意味着文件库不会将文件解释为文本,并且与响应中返回的内容类型无关。

你的代码的问题是你总是返回一个“文本/纯”的内容类型。上面的代码不返回任何内容类型,但如果您只是将其用于HTML、CSS和JS,浏览器可以很好地推断出这些内容。没有内容类型总比错误的内容类型好。

通常情况下,content-type是web服务器的配置。因此,如果这不能解决您的问题,我很抱歉,但是作为一个简单的开发服务器,它对我来说是有效的,我认为它可能对其他人有所帮助。如果确实需要响应中正确的内容类型,则需要像joeytwiddle那样显式地定义它们,或者使用像Connect这样具有合理默认值的库。这样做的好处是它简单且自包含(没有依赖)。

但我确实感觉到了你的问题。这就是组合解。

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  var contentTypesByExtension = {
    '.html': "text/html",
    '.css':  "text/css",
    '.js':   "text/javascript"
  };

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      var headers = {};
      var contentType = contentTypesByExtension[path.extname(filename)];
      if (contentType) headers["Content-Type"] = contentType;
      response.writeHead(200, headers);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

如果你的电脑上安装了节点,你可能有NPM,如果你不需要NodeJS的东西,你可以使用服务包来实现这个:

1 -在您的PC上安装软件包:

npm install -g serve

2 -提供静态文件夹:

serve <path> 
d:> serve d:\StaticSite

它会告诉你你的静态文件夹正在被服务的端口,只需像这样导航到主机:

http://localhost:3000
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'

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

这是一个最快的解决方案,我用快速看到网页

sudo npm install ripple-emulator -g

从那时起,只需输入html文件的目录并运行

ripple emulate

然后将设备更改为Nexus 7横屏。