Using node.js as a simple web server

后端 未结 30 2237
感情败类
感情败类 2020-11-22 02:54

I want to run a very simple HTTP server. Every GET request to example.com should get index.html served to it but as a regular HTML page (i.e., same

30条回答
  •  被撕碎了的回忆
    2020-11-22 03:20

    from w3schools

    it is pretty easy to create a node server to serve any file that is requested, and you dont need to install any packages for it

    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

    will serve file.html from disk

提交回复
热议问题