如何使用Node创建Web服务器

2016-09-02 21:16:21 6242

Node.js提供了可以用于创建任何HTTP服务器的客户端的HTTP模块。以下是HTTP服务器的最低限度的结构,它会在8081端口侦听。

创建一个js文件名为server.js:

var http = require('http');var fs = require('fs');var url = require('url');// Create a serverhttp.createServer( function (request, response) {  
   // Parse the request containing file name
   var pathname = url.parse(request.url).pathname;
   
   // Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");
   
   // Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         // HTTP Status: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{	
         //Page found	  
         // HTTP Status: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});	
         
         // Write the content of the file to response body
         response.write(data.toString());		
      }
      // Send the response body 
      response.end();
   });   }).listen(8081);// Console will print the messageconsole.log('Server running at http://www.landui.com:8081/');

接下来,让我们?建以下名为index.html的HTML文件在创建server.js的同一目录下

File: index.html


<html>

<head>

<title>Sample Page</title>

</head>

<body>

Hello World!

</body>

</html>


现在让我们运行server.js看到的结果:


$ node server.js

验证输出


Server running at http://www.landui.com:8081/

blob.png

提交成功!非常感谢您的反馈,我们会继续努力做到更好!

这条文档是否有帮助解决问题?

非常抱歉未能帮助到您。为了给您提供更好的服务,我们很需要您进一步的反馈信息:

在文档使用中是否遇到以下问题: