天天看点

Node.js学习笔记(十五、Web模块)

其实在前面,已经多次应用过Node.js Web模块,比如路由,由index.js提供一个接口去调用相应的路由模块和Web模块。

Web服务器是什么?

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

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

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

Web架构

web架构分为客户端、服务层、业务层、数据层等层级。

Node.js学习笔记(十五、Web模块)

.Client:客户端,B/S架构下一般指的是浏览器,浏览器可以通过 HTTP 协议向服务器请求数据。

 .Server:服务端,一般指 Web 服务器,可以接收客户端请求,并向客户端发送响应数据

 .Business:业务层, 通过 Web 服务器处理应用程序,如与s数据层交互,逻辑运算,调用外部程序等。

 .Data: 数据层,一般由数据库和数据持久化模块组成。

创建 Web 服务器

创建web服务器的核心对象是http模块,用 HTTP 服务器或客户端功能必须调用 http 模块。

var http = require('http');      

实例,这是一个基本的http服务架构:

webServer.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/html
            response.writeHead(404, {'Content-Type': 'text/html'});
        }else{
            // HTTP 状态码: 200 : OK
            // Content Type: text/html
            response.writeHead(200, {'Content-Type': 'text/html'});

            // 响应文件内容
            response.write(data.toString());
        }
        //  发送响应数据
        response.end();
    });
}).listen(8080);

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

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>随便试试</title>
</head>
<body>
  <h1>脑瓜子嗡嗡的</h1>
</body>
</html>      

运行webServer.js:

Node.js学习笔记(十五、Web模块)

访问地址:

http://127.0.0.1:8080/index.html
Node.js学习笔记(十五、Web模块)
Node.js学习笔记(十五、Web模块)

报了点错,好像是图标的问题。

创建客户端

实例,client.js:

var http = require('http');

// 用于请求的选项
var options = {
    host: 'localhost',
    port: '8080',
    path: '/index.html'
};

// 处理响应的回调函数
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();      

服务端运行的前提下,另外用一个终端运行cllient.js:

Node.js学习笔记(十五、Web模块)

服务端结果:

Node.js学习笔记(十五、Web模块)

参考:

【1】、

https://www.runoob.com/nodejs/nodejs-web-module.html

【2】、

https://www.w3cschool.cn/nodejs/nodejs-web-module.html