美文网首页我爱编程
使用 Node.js 搭建 Web 服务器

使用 Node.js 搭建 Web 服务器

作者: 喵了个咪O_O | 来源:发表于2018-06-08 14:44 被阅读0次

    一 Web服务器

    1. Web服务器的功能

    1). 接收http请求 ( GET, POST) restful(DELETE, PUT, PATCH)

    2). 处理HTTP请求 (自己处理, 或请求别的程序处理)
    做出响应 (返回页面, 文件, 各类数据等)

    2. 常见的Web架构

    1). Nginx/Apache: 负责接受HTTP请求, 确定谁来处理请求, 并返回请求的结果

    1. php-fpm/php模块 : 处理分配给自己的请求, 并将处理结果返回给分配者
    3. 常见的请求种类

    1). 请求文件: 包括静态文件(网页, 图片吗前端JavaScript文件, css文件...), 及由程序处理得到的文件

    2). 完成指定的操作: 如登录, 获取特定数据等

    二 Node.js 的Web服务器

    特性:
    1). 不依赖其他特性的Web服务软件 (如 Apache, Nginx, IIS...)
    2). Node.js代码处理请求的逻辑
    3). Node.js代码负责Web服务器的各种 "配置"

    1. 使用Node.js的核心模块http搭建Web服务器

    1). 创建web.js

    //  web.js
    //  引入http模块
    var http = require('http')
    
    //设置请求监听函数
    /**
      *  param req:   请求信息
      *  param res:   响应信息
      */
    var requestHandler = function (req, res) {
                res.end('hello');
        }
    
    //创建服务器
    var web = http.createServer(requestHandler)
    
    //设置监听端口号
    web.listen(7878)
    
    console.log('http running on http://localhost:7878')
    

    2). $ node web.js


    01.png

    3).测试服务器是否搭建成功
    方法一: 新建一个终端窗口运行命令
    $ curl http://localhost:7878
    方法二: 浏览器中打开地址
    http://localhost:7878

    02.png

    2. 使用express搭建服务器

    1). 安装express库

    $  cd express.js   
    $  npm install express
    

    2). 新建文件express.js

    //引入express的模块
    var express = require('express');
    
    //创建实例
    var app = express();
    
    //静态文件
    // http://exapmle.com/static.file
    app.use(express.static('./public'));
    
    app.get('/', function (req, res, next) {
      res.end('hello \n')
      next();
    })
    
    //设定监听端口, 和回调函数
    app.listen(7878, function afterListen() {
      console.log('express running on http://localhost:7878');
    });
    

    3). 测试服务器是否创建成功
    方法一: 新建一个终端窗口运行命令

    $ curl http://localhost:7878
    

    方法二: 浏览器中打开地址

    http://localhost:7878
    

    3. 搭建TCP服务器

    1). 使用net模块创建TCP服务器

    2). 使用telnet链接TCP服务器 - 使用telnet进行测试

    1. 安装telnet
      $ brew install telnet
    2. 测试链接
      $ telnet localhost 18001 //telnet 地址 端口号
    3. 直接输入内容回车即可发送数据
      buffer是用来处理二进制和非unicode数据的类, tcp通讯中传输的原始数据, 在nodejs中便是使用buffer的实例来进行封装的
    4. 查看当前系统使用的端口号
      1) netstat 命令 grep筛选结果
      netstat -an | grep 18001 2) lsof命令 lsof -i :18001
    1. 查看telnet的进程 杀死进程, 查看链接关闭的效果
    //  tcp.js
    
    const PORT = 18001;
    const HOST = '127.0.0.1';
    
    //导入核心模块
    var net = require('net');
    
    //监听函数
    var clientHandler = function (socket) {
        console.log('someone connected');
    
        //服务器端收到客户端发送的数据
        socket.on('data', function dataHandler(data) {
            console.log(socket.remoteAddress, socket.remotePort, 'send', data.toString())
    
            //服务器端向客户端发送数据
            socket.write('server received \n')
        });
    
        //链接断开
        socket.on('close', function () {
            console.log(socket.remoteAddress, socket.remotePort, 'connect close')
        })
    
    }
    
    //创建服务器
    var app = net.createServer(clientHandler);
    
    app.listen(PORT, HOST);
    
    console.log('TCP server running on tcp://', HOST, ':', PORT);
    
    1. 使用net创建TCP客户端
    //  tcpClient.js
    
    var net = require('net');
    
    const HOST = '127.0.0.1';
    
    const PORT = 18001;
    
    
    var tcpClient = net.Socket();
    
    tcpClient.connect(PORT, HOST, function () {
        console.log('connect success');
        tcpClient.write('this is tcp client by Node.js');
    });
    
    //接受服务器端的数据
    tcpClient.on('data', function (data) {
        console.log('receive: ', data.toString())
    })
    
    

    三. express

    1. 使用express创建路由的三种方法

    1) . path
    //path 方法
    app.get('/', function (req, res, next) {
        res.send('express hello')
        res.end(' hello\n')
        next();
    })
    
    屏幕快照 2018-06-08 下午2.17.14.png
    2). Router
    var Router = express.Router();
    
    /**
     * http:/example.com/post/add
     * http:/example.com/post/list
     */
    
    Router.get('/add', function (req, res) {
        res.end('Router add\n' );
    })
    
    Router.get('/list', function (req, res) {
        res.end('Router list\n' );
    })
    
    app.use('/post', Router)
    
    router.png
    3). route
    //指定不同方法下的不同的处理, 如post请求和get请求执行的操作
    //http://example.com/article
    
    app.route('/article')
        .get(function (req, res) {
            res.end('route /article get \n')
        })
        .post(function (req, res) {
            res.end('route /article post\n')
        })
    

    命令行发起post请求和get请求

    //get请求
    curl http://localhost:7878 或 curl -X GET http://localhost:7878

    //post请求
    $ curl -X POST http://localhost:7878

    get/post请求.png
    2. 指定参数名
    //http://example.com/news/123
    app.param('newsId', function(res, req, next, newsId) {
        req.newId = newsId;//将newId赋值给请求参数
        next();//请求完执行的函数
    })
    
    app.get('/news/:newsId', function (req, res) {
        console.log(req.params)
        res.end('newId: ' + req.params.newsId + '\n');
    })
    

    3. 中间件

    Connect: Node.js 的中间件架构
    分层处理
    每层实现一个功能
    以打印日志中间件 morgan 为例

    1.安装morgan
    $ npm install morgan

       var morgan = require('morgan');  //打印日志
    
       //中间件
       app.use(morgan());
    

    4. 自动生成 express应用模板

    express生成工具, 直接生成express应用模板
    全局 安装 express-generator
    npm install -g express-generator express expressHello/
    cd expressHello vim package.json 查看执行目录 /bin/www.js
    npm install 执行模块安装, 因为已经定义好了, 所以直接执行instal node bin/www
    $ curl http://localhost:3000 默认端口号实3000, 链接服务器测试

    5. express的完整代码

    //引入express的模块
    var express = require('express');
    var morgan = require('morgan');  //打印日志
    
    //创建实例
    var app = express();
    
    //中间件
    app.use(morgan());
    
    //静态文件
    app.use(express.static('./public'));
    
    //path 方法
    app.get('/', function (req, res, next) {
        res.send('express hello \n');
        next();
    });
    
    //Router 方法
    var Router = express.Router();
    /**
     * http:/example.com/post/add
     * http:/example.com/post/list
     */
    
    Router.get('/add', function (req, res) {
        res.end('Router add\n' );
    });
    
    Router.get('/list', function (req, res) {
        res.end('Router list\n' );
    });
    
    app.use('/post', Router);
    
    //route 方法
    //指定不同方法下的不同的处理, 如post请求和get请求执行的操作
    app.route('/article')
        .get(function (req, res) {
            res.end('route /article get \n')
        })
        .post(function (req, res) {
            res.end('route /article post\n')
        });
    
    //http://example.com/news/123
    //指定参数名
    app.param('newsId', function(res, req, next, newsId) {
        req.newsId = newsId;//将newId赋值给请求参数
        next();//请求完执行的函数
    });
    
    app.get('/news/:newsId', function (req, res) {
        console.log(req.params);
        res.end('newsId: ' + req.params.newsId + '\n');
    });
    
    
    //设定监听端口, 和回调函数
    app.listen(7878, function afterListen() {
        console.log('express running on http://localhost:7878');
    });
    

    相关文章

      网友评论

        本文标题:使用 Node.js 搭建 Web 服务器

        本文链接:https://www.haomeiwen.com/subject/vqzgsftx.html