Node.js学习第五天笔记

day05

express

  1. 后端渲染一个页面
  2. api接口

问题: 如果遇到了前后端不分离的项目, 你怎么做?

  1. 找后端,搭建项目启动的环境
  2. 找后端模板引擎 ( 找类似于 view 这样的目录 )
  3. 找静态资源文件目录
  4. 找对应性文件, index.ejs index.css
  5. 看效果改js 看效果改css

api接口暴露

测试接口是否正常,我们可以使用测试工具:postman insomnia

BE: BackEnd 后端

  • express中一个路由即一个接口

  • api接口暴露的方式有两种:

    • 第一种: 使用模板进行暴露,但是要将数据做字符串转换,然后使用ejs的非转义输出
      router.get('/',function( req,res,next ) {
        res.render('mine', {
          mine: JSON.stringify({
            ret: true,
            username: 'yyb',
            password: 123
          })
        })
      })
    
    • 第二种: 使用json()
      router.get('/',function( req,res,next ) {
        res.json({
          ret: true,
           username: 'yyb',
           password: 123
         })
      })
    

通信

前端三种通信形式

  1. 一种是基于后端的
    • 基于net模块的socket
  2. 另外两种是基于前端
    • H5 提供的 webSocket
    • 低版本pc端使用的 socket.io

关于通信和里面用到的几个函数请参考如下博客

  - https://blog.csdn.net/u011146511/article/details/79501036
  - 几个方法
    主要应用到的函数有5个:

    .on('connection', function(socket){ }):与客户端建立连接时监听。

    .on('disconnect', function(){ }):与客户端断开连接时监听。

    .on('event-name', function(data) { }):监听客户端发来的消息。

    .broadcast.emit('event-name', { }):向除自己外的所有其他用户广播消息。

    .emit('event-name', { }):仅向当前连接的客户端(自己)推送消息。

    // 服务端
     // io.on(‘connection’,function(socket));//监听客户端连接,回调函数会传递本次连接的socket
     //
     // io.sockets.emit(‘String’,data);//给所有客户端广播消息
     //
     // io.sockets.socket(socketid).emit(‘String’, data);//给指定的客户端发送消息
     //
     // socket.on(‘String’,function(data));//监听客户端发送的信息
     //
     // socket.emit(‘String’, data);//给该socket的客户端发送消息
    --------------------- 

作业:

  1. 使用express 渲染 一个二阶段 页面
  2. 使用express暴露接口(restful api)
  3. 阅读前端开发文档规范
  4. 复习Node.js

express框架的一些 使用方面的知识

  1. .ejs文件相当于html文件,只是ejs把html文件优化的的性能更优
  2. 在WWW文件中更改运行服务器
          server.listen(port,function(){
      console.log('服务器运行在:http://localhost:3000')
    });
    server.on('error', onError);
    server.on('listening', onListening);
    
  3. 可以吧css文件放在stylesheets文件中
  4. 吧图片放在images文件中
  5. 在routes文件中可以编写js文件
    1. 如数据的接口的模拟
                   var express = require('express');
           var router = express.Router();
      
           /* GET home page. */
           router.get('/', function(req, res, next) {
             res.render('index', {
               
               title: 'ghdshhgiwgeui',
             
               name: '1902',
               flag: false,
               student: {
                 id: 1,
                 name: 'gashgewigqigwi'
               },
               todolist: [
                 {
                   id: 1, 
                   task: '撸猫'
                 },
                 {
                   id: 2,
                   task: '备课'
                 }
               ]
             
             
             });
           });
      
           module.exports = router;
      
      
    2. 路径路由/中间介
                const express=require('express')
        const router = express.Router()
    
        //router.get(路径路由, 中间介)
        router.get('/login',function(req,res,next){
        res.render('login',{
            username:'gch',
            password:123
        })
        })
        module.exports=router
    
    
    1. .ejs的输出
                <!DOCTYPE html>
        <html>
          <head>
            <title><%= title %></title>
            <link rel='stylesheet' href='/stylesheets/style.css' />
          </head>
          <body>
            <h1> hello 5200 </h1>
            <p> hello 老彭 </p>
            <p> name: <%= name%> </p>
            <h3> ejs条件判断语法 </h3>
            <% if( flag ) { %>
              <p> 这是ejs条件判断语法 </p>
            <% }else { %>
              <p> else </p>
            <%}%>
            <h3> <%= %> </h3>
            <p> <%= title%> </p>
            <h3> <%- %> </h3>
            <p> <%- student %> </p>
    
            <h3> ejs 循环输出列表 </h3>
    
            <ul>
              <% todolist.forEach( function ( item ) { %>
                <li> <%= item.task %> </li>
              <% }) %> 
            </ul>
    
            <img src="https://www.baidu.com/img/bd_logo1.png?where=super" alt="">
    
          </body>
        </html>
    
    
  6. package.json文件的配置
      {
        "name": "3-express",
        "version": "0.0.0",
        "private": true,
        "scripts": {
          "start": "nodemon ./bin/www"
        },
        "dependencies": {
          "cookie-parser": "~1.4.4",
          "debug": "~2.6.9",
          "ejs": "~2.6.1",
          "express": "~4.16.1",
          "http-errors": "~1.6.3",
          "morgan": "~1.9.1"
        }
      }
    
    
  7. 运行服务器用
    $ npm run start

接口的暴露于获取

  1. 在routes文件中写js文件进行配置(用于暴露接口)
        const express = require( 'express' )

      const router = express.Router()

      //api接口   restful api规则 

      router.get('/',function( req,res,next ) {
        let { username,password } = req.query
        res.render('mine', {
          mine: JSON.stringify({
            ret: true,
            username,
            password
          })
        })
      })

      router.post('/',function( req,res,next) {
        let { username,password } = req.body
        res.render('mine',{
          mine: JSON.stringify({
            ret: true,
            username,
            password
          })
        })
      })


      router.put('/',function ( req,res,next ) {
        res.render('mine',{
          mine: JSON.stringify({
            ret: true,
            text: '增加'
          })
        })
      })  

      router.delete('/',function ( req,res,next ) {
        res.render('mine',{
          mine: JSON.stringify({
            ret: true,
            text: '删除'
          })
        })
      })  


      // router.all('/',function( req,res,next ) {
      //   res.render('mine',{
      //     mine: JSON.stringify({
      //       ret: true,
      //       text: 'all'
      //     })
      //   })
      // })


      /* 
        应用场景: 
          你之前用 post 暴露的那个接口,那个前端接收不到,要不你给改成get ?


          那个前端又拿到了, 你要不在改回来吧 


          get  post   put 


          千万记住,项目上线一定要改回来
      */





      module.exports = router
  1. 用insomnia软件进行测试 get post put

关于通信Socket

        const net = require( 'net' )

        // 命令行的读入和命令行的读出 -- start
        const readline = require( 'readline' )

        // 命令行的读入和命令行的读出 -- end

        const socket = new net.Socket()

        const port = 8000

        const hostname = '127.0.0.1'

        socket.setEncoding = 'UTF-8'

        socket.connect( port,hostname,function(){
          socket.write('hello 小姐姐好~~')
        })

        socket.on( 'data', function ( msg ) {
          console.log( msg )
          say()
        })

        socket.on( 'error', function ( error ) {
          console.log( 'error' + error )
        }) 

        socket.on('close',function(){
          console.log('下线了')
        })

        const rl = readline.createInterface({
          input: process.stdin,
          output: process.stdout
        })

        function say () {
          console.log( 'say ')
          rl.question('请输入: ', ( answer ) => {
            // TODO: Log the answer in a database
            
            if( answer === 'bye'){
              rl.close();
            }else{
              socket.write( answer + '\n')
            }
          })
        }
      const net = require( 'net' )
    const port = 8000
    const hostname = '127.0.0.1'

    // 定义两个变量, 一个用来计数,一个用来保存客户端

    let clients = {}
    let clientName = 0

    // 创建服务器

    const server = new net.createServer()

    server.on('connection', ( client ) => {
      client.name = ++clientName // 给每一个client起个名
      clients[client.name] = client // 将client保存在clients

      client.on( 'data', function ( msg ) { //接收client发来的信息
        console.log(`客户端${ client.name }发来一个信息:${msg}`)
      })

      client.on('error', function ( e ) { //监听客户端异常
        console.log( 'client error' + e )
        client.end()
      })

      client.on( 'close', function () {
        delete clients[client.name]
        console.log('客户端下线了')
      })

    })

    server.listen( port,hostname,function () {
      console.log(`服务器运行在: http://${ hostname }:${ port  }`)
    })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值