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


当前回答

从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

其他回答

我认为你现在忽略的部分是你在发送:

Content-Type: text/plain

如果你想要一个web浏览器来呈现HTML,你应该将其更改为:

Content-Type: text/html

我也可以推荐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")
        }
    }
}

这基本上是连接版本3的公认答案的更新版本:

var connect = require('connect');
var serveStatic = require('serve-static');

var app = connect();

app.use(serveStatic(__dirname, {'index': ['index.html']}));
app.listen(3000);

我还添加了一个默认选项,以便index.html作为默认选项。

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中的相对路径!

拖鞋!

从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