本节介绍node.js web模块,首先,你应该先了解什么是web服务器。


什么是 web 服务器?

web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序。

web服务器的基本功能就是提供web信息浏览服务。它只需支持http协议、html文档格式及url,与客户端的网络浏览器配合。

大多数web服务器都支持服务端的脚本语言(php、python、ruby)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。

目前最主流的三个web服务器是apache、nginx、iis。


web 应用架构

  • client - 客户端,一般指浏览器,浏览器可以通过http协议向服务器请求数据。

  • server - 服务端,一般指web服务器,可以接收客户端请求,并向客户端发送响应数据。

  • business - 业务层, 通过web服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。

  • data - 数据层,一般由数据库组成。


使用 node 创建 web 服务器

node.js提供了http模块,http模块主要用于搭建http服务端和客户端,如果要使用http服务器或客户端功能,则必须调用http模块,代码如下:

var http = require('http');

以下是演示一个最基本的http服务器架构(使用8081端口),创建server.js文件,代码如下所示:

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


// 创建服务器
http.createserver( function (request, response) {  
   // 解析请求,包括文件名
   var pathname = url.parse(request.url).pathname;
   
   // 输出请求的文件名
   console.log("request for " + pathname + " received.");
   
   // 从文件系统中读取请求的文件内容
   fs.readfile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         // http 状态码: 404 : not found
         // content type: text/plain
         response.writehead(404, {'content-type': 'text/html'});
      }else{	         
         // http 状态码: 200 : ok
         // content type: text/plain
         response.writehead(200, {'content-type': 'text/html'});	
         
         // 响应文件内容
         response.write(data.tostring());		
      }
      //  发送响应数据
      response.end();
   });   
}).listen(8081);

// 控制台会输出以下信息
console.log('server running at http://127.0.0.1:8081/');

接下来我们在该目录下创建一个index.htm文件,代码如下:

<html>
<head>
<title>sample page</title>
</head>
<body>
hello world!
</body>
</html>

执行server.js文件:

$ node server.js
server running at http://127.0.0.1:8081/

接着我们在浏览器中输入并打开地址:http://127.0.0.1:8081/index.htm,显示如下图所示: