zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Node.js 搭建Web服务器和Web客户端

2023-09-11 14:22:55 时间

服务器定义

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

Web 应用架构

这里写图片描述

 1. Client - 客户端,一般指浏览器,浏览器可以通过 HTTP 协议向服务器请求数据。
 2. Server - 服务端,一般指 Web 服务器,可以接收客户端请求,并向客户端发送响应数据。
 3. Business - 业务层, 通过 Web 服务器处理应用程序,如与数据库交互,逻辑运算,调用外部程序等。
 4. Data - 数据层,一般由数据库组成。

文档目录结构

这里写图片描述
这里写图片描述

代码实战

1、htmlDemo.js

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

http.createServer(function(request, response) {
    var pathname = url.parse(request.url).pathname;
    var readDir = path.join(__dirname, 'public');
    //默认路径是命令行的路径,而不是js文件的路径
    //不仅是html文件,所用到的资源(image、css、js等)都会在该函数被请求
    //html里的图片不能访问到它的上一级目录
    console.log('Request for pathname = ' + pathname);
    var subPathname = pathname.substr(1);
    if(!subPathname) {
        subPathname = 'index.html';
    }
    if(!path.extname(subPathname)) {
        subPathname+='.html';
    }
    console.log('after modify pathname = ' + subPathname);
    var readPath = path.join(readDir, subPathname);
    console.log(readPath);
    fs.readFile(readPath, function(err, data) {
        if(!err) {
            response.writeHead(200, {'Content-Type':'text/html'});
            response.end(data);
        } else {
            console.log(err);
            response.writeHead(404, {'Content-Type':'text/html'});
            fs.readFile(path.join(readDir, '404.html'), function(err, data) {
                if(err) {
                    console.log(err);
                    response.end();
                } else {
                    response.end(data);
                }
            });
        }
    });
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080');

http.request({host:'localhost', port:'8080', path:'/index.html'}, function(response){
    //注意这里必须先赋空值,否则会加入'undefined'字符串
    var body = '';
    //一直有数据,需要不断的更新
    response.on('data', function(data){
        //调用多少次response.write和end就会触发多少次on('data')事件
        console.log('response.on data emitter');
        body += data;
    }).on('end', function(){
        console.log('response.on end emitter');
        console.log(body);
    });
}).end();

2、index.html

<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>

3、404.html

<html>
    <head>
        <title>404 File Not Found</title>
    </head>
    <body>
        <img src="images/404.jpg" width="100%" height="100%" />
    </body>
</html>

运行截图

这里写图片描述