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


当前回答

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

拖鞋!

其他回答

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

拖鞋!

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>

从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

与其处理switch语句,我认为从字典中查找内容类型更简洁:

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

...

    var contentType = contentTypesByExtension[fileExtension] || 'text/plain';

你不需要快递。你不需要联系。Node.js执行http native。你所需要做的就是根据请求返回一个文件:

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

http.createServer(function (request, response) {
    var requestUrl = url.parse(request.url)    
    response.writeHead(200)
    fs.createReadStream(requestUrl.pathname).pipe(response)  // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync) 
}).listen(9615)    

一个更完整的例子,确保请求不能访问基目录下的文件,并进行适当的错误处理:

var http = require('http')
var url = require('url')
var fs = require('fs')
var path = require('path')
var baseDirectory = __dirname   // or whatever base directory you want

var port = 9615

http.createServer(function (request, response) {
    try {
        var requestUrl = url.parse(request.url)

        // need to use path.normalize so people can't access directories underneath baseDirectory
        var fsPath = baseDirectory+path.normalize(requestUrl.pathname)

        var fileStream = fs.createReadStream(fsPath)
        fileStream.pipe(response)
        fileStream.on('open', function() {
             response.writeHead(200)
        })
        fileStream.on('error',function(e) {
             response.writeHead(404)     // assume the file doesn't exist
             response.end()
        })
   } catch(e) {
        response.writeHead(500)
        response.end()     // end the response so browsers don't hang
        console.log(e.stack)
   }
}).listen(port)

console.log("listening on port "+port)