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


当前回答

你不需要快递。你不需要联系。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)

其他回答

Node.js webserver


没有第三方框架;允许查询字符串;添加尾随斜杠;处理404


创建一个public_html子文件夹,并将所有内容放在其中。


要点:https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3

var fs = require('fs');

require('http').createServer(function(request, response) {
  var path = 'public_html'+ request.url.slice(0,
      (request.url.indexOf('?')+1 || request.url.length+1) - 1);
      
  fs.stat(path, function(bad_path, path_stat) {
    if (bad_path) respond(404);
    else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
      response.setHeader('Location', path.slice(11)+'/');
      respond(301);
    } else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
          function(bad_file, file_content) {
      if (bad_file) respond(404);
      else respond(200, file_content);
    });
  });
 
  function respond(status, content) {
    response.statusCode = status;
    response.end(content);
  }
}).listen(80, function(){console.log('Server running on port 80...')});

步骤1(在命令提示符[I hope you cd TO YOUR FOLDER]内):npm install express

步骤2:创建一个server.js文件

var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use(express.static(__dirname + "/public")); //use static files in ROOT/public folder

app.get("/", function(request, response){ //root dir
    response.send("Hello!!");
});

app.listen(port, host);

请注意,您也应该添加WATCHFILE(或不使用demon)。以上代码仅用于一个简单的连接服务器。

步骤3:node server.js或nodemon server.js

现在有一个更简单的方法,如果你只是想主机简单的HTTP服务器。 NPM install -g http-server

打开目录,输入http-server

https://www.npmjs.org/package/http-server

注:此答案来自2011年。然而,它仍然有效。

你可以在Node.js中使用Connect和ServeStatic:

使用NPM安装connect和service -static $ NPM install connect service -static 创建server.js文件,内容如下: Var connect = require('connect'); var serveStatic = require(' service -static'); connect () .use (serveStatic (__dirname)) .listen(8080, () => console.log('服务器运行在8080…')); 使用Node.js运行 $ node server.js

您现在可以访问http://localhost:8080/yourfile.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

这里有很多复杂的答案。如果你不打算处理nodeJS文件/数据库,只是想提供静态html/css/js/图像,就像你的问题建议的那样,然后简单地安装pushstate-server模块或类似的;

这是一个“一行程序”,它将创建并启动一个迷你网站。只需将整个块粘贴到终端中相应的目录中。

mkdir mysite; \
cd mysite; \
npm install pushstate-server --save; \
mkdir app; \
touch app/index.html; \
echo '<h1>Hello World</h1>' > app/index.html; \
touch server.js; \
echo "var server = require('pushstate-server');server.start({ port: 3000, directory: './app' });" > server.js; \
node server.js

打开浏览器,访问http://localhost:3000。完成了。

服务器将使用应用程序目录作为根目录来提供文件。要添加额外的资产,只需将它们放在该目录中。