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


当前回答

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

sudo npm install ripple-emulator -g

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

ripple emulate

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

其他回答

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

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");

从w3schools

创建一个节点服务器来服务任何被请求的文件是很容易的,你不需要为它安装任何包

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    }  
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

http://localhost:8080/file.html

将从磁盘上提供file.html

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

sudo npm install ripple-emulator -g

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

ripple emulate

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

我也可以推荐SugoiJS,它很容易设置,并提供了一个快速开始编写的选项,有很好的功能。

看看这里:http://demo.sugoijs.com/ ,文档:https://wiki.sugoijs.com/

它具有请求处理装饰器、请求策略和授权策略装饰器。

例如:

import {Controller,Response,HttpGet,RequestParam} from "@sugoi/server";
​
@Controller('/dashboard')
export class CoreController{
    constructor(){}
​
    @HttpGet("/:role")
    test(@RequestParam('role') role:string,
         @RequestHeader("role") headerRole:string){
        if(role === headerRole )
            return "authorized";
        else{
            throw new Error("unauthorized")
        }
    }
}
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/html'});
    // change the to 'text/plain' to 'text/html' it will work as your index page
    res.end(index);
}).listen(9615);

我想你是在找这个。在index.html中,简单地用普通的html代码填充它-无论你想在上面渲染什么,比如:

<html>
    <h1>Hello world</h1>
</html>