Node.js Web 模块

 


什么是 Web 服务器?

Web服务器通常指网站服务器,是指驻留于因特网上某种类型计算机的程序,Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。php

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

 

目前最主流的三个Web服务器是Apache、Nginx、IIS。node


Web 应用架构

  • Client - 客户端,通常指浏览器,浏览器能够经过 HTTP 协议向服务器请求数据。python

  • Server - 服务端,通常指 Web 服务器,能够接收客户端请求,并向客户端发送响应数据。web

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

  • Data - 数据层,通常由数据库组成。浏览器


使用 Node 建立 Web 服务器

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

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,显示以下图所示:

执行 server.js 的控制台输出信息以下:

Server running at http://127.0.0.1:8081/ Request for /index.htm received. # 客户端请求信息


使用 Node 建立 Web 客户端

Node 建立 Web 客户端须要引入 http 模块,建立 client.js 文件,代码以下所示:

var http = require('http'); // 用于请求的选项 var options = { host: 'localhost', port: '8081', path: '/index.htm' }; // 处理响应的回调函数 var callback = function(response){ // 不断更新数据 var body = ''; response.on('data', function(data) { body += data; }); response.on('end', function() { // 数据接收完成 console.log(body); }); } // 向服务端发送请求 var req = http.request(options, callback); req.end();

新开一个终端,执行 client.js 文件,输出结果以下:

$ node client.js <html> <head> <title>Sample Page</title> </head> <body> Hello World! </body> </html>

执行 server.js 的控制台输出信息以下:

Server running at http://127.0.0.1:8081/ Request for /index.htm received. # 客户端请求信息
相关文章
相关标签/搜索