zoukankan      html  css  js  c++  java
  • node http 模块 常用知识点记录

    关于 node,总是断断续续的学一点,也只能在本地自己模拟实战,相信总会有实战的一天~~

    • http 作为服务端,开启服务,处理路由,响应等
    • http 作为客户端,发送请求
    • http、https、http2 开启服务

    作为服务端

    1. 开启服务,有两种方式

    方式1

    const http = require('http')
    
    // 开启服务
    var server = http.createServer(function (req, res) {
      // 开启服务后具体做什么
      res.end('hello world')
    }).listen(3000);
    

    方式2

    const http = require('http')
    const server = new http.Server()
    // node 中的服务都是继承 eventemit
    
    // 开启服务
    server.on('request', function () 
      // 开启服务后具体做什么
      res.end('hello world')
    })
    server.listen(3000)
    
    1. 路由

    路由的原理:根据路径去判断

    const http = require('http')
    const server = new http.Server();
    server.on('request', function () {
      var path = req.url;
      switch (path) {
        case '/':
          res.end('this is index');
          // res.end('<a href="./second">second</a>');
          break;
        case '/second':
          res.end('this is second');
          break;
        default:
          res.end('404');
          break;
      }
    })
    server.listen(3000)
    
    1. 获取请求头信息、设置响应头
    const http = require('http')
    const server = new http.Server();
    server.on('request', function () {
    
      // 设置响应头:setHeader() / writeHead()
      // setHeader 设置多次,每次一个
      res.setHeader('xxx', 'yyy');
      res.setHeader('aaa', 'yyy');
      res.setHeader('bbb', 'yyy');
      
      // writeHead 只能设置一次,多个,会合并setHeader中的信息,同名优先级高
      res.writHead(200, {
        'content-type': 'text/html;charset=utf-8', //'text/plain;charset=utf-8'
        'ccc': 'yyy',
        'aaa': 'aaa'
      })
    
      // 需要先设置响应头,再设置res.end,需要先设置setHeader,再设置res.writHead
      
    
      // 请求头信息
      console.log(req.httpVersion)
      console.log(req.method)
      console.log(req.url)
      console.log(http.STATUS_CODES)
    
      // 比如根据请求头进行:token处理
      var token = md5(req.url + req.headers['time'] + 'dsjaongaoeng');
      if (req.headers['token'] == token) {
        res.end()
      } else {
        res.end()
      }
    
    })
    server.listen(3000)
    
    1. 常用监听事件
    const http = require('http')
    const server = new http.Server();
    server.on('request', function () {
    
      // 请求监听
      // 每次有数据过来
      req.on('data', function (chunk) {
    
      })
      // 整个数据传输完毕
      req.on('end', function () {
    
      })
    
      // 响应监听
      res.on('finish', function () {
        console.log('响应已发送')
      })
    
      res.on('timeout', function () {
        res.end('服务器忙')
      })
      res.setTimeout(3000)
    
    })
    
    // 连接
    server.on('connection', function () {
    
    })
    
    // 错误处理
    server.on('error', function (err) {
      console.log(err.code)
    })
    
    // 超时 2000 ms
    server.setTimeout(2000, function () {
      console.log('超时')
    })
    
    server.listen(3000)
    
    
    1. 接受 get 和 post 请求
    const http = require('http')
    const url = require('url')
    const server = new http.Server();
    server.on('request', function () {
      
      // get 参数,放在url中,不会触发 data
      var params = url.parse(req.url, true).query;
      // post 参数,在请求体中,会触发 data
      var body = ""
      req.on('data', function (thunk) {
        body += chunk
      })
      req.end('end', function () {
        console.log(body)
      });
    
    })
    
    server.listen(3000)
    

    http 作为客户端

    1. 发送请求:request 发送 post 请求,get 发送 get 请求
    const http = require('http')
    
    const option = {
      hostname: '127.0.0.1',
      port: 3000,
      method: 'POST',
      path: '/', // 可不写,默认到首页
      headers: {
        'Content-Type': 'application/json'
      }
    }
    // post 
    var req = http.request(option, function (res) {
      // 接收响应
      var body = ''
      res.on('data', function (chunk) {
        body += chunk
      })
      res.on('end', function () {
        console.log(body)
      })
    });
    
    var postJson = '{"a": 123, "b": 456}'
    req.write(postJson)
    req.end(); // 结束请求
    
    // get
    http.get('http://localhost:3000/?a=123', function (req) {
      // 接收响应
      var body = ''
      res.on('data', function (chunk) {
        body += chunk
      })
      res.on('end', function () {
        console.log(body)
      })
    });
    
    1. 设置请求头和响应头
    const http = require('http')
    
    const option = {
      hostname: '127.0.0.1',
      port: 3000,
      method: 'POST',
      path: '/', // 可不写,默认到首页
      headers: { // 可在此设置请求头
        'Content-Type': 'application/json'
      }
    }
    // post 
    var req = http.request(option, function (res) {
      // 避免乱码
      res.setEncoding('utf-8')
      // 获取响应头
      console.log(res.headers)
      console.log(res.statusCode)
    
      // 接收响应
      var body = ''
      res.on('data', function (chunk) {
        body += chunk
      })
      res.on('end', function () {
        console.log(body)
      })
    });
    
    var postJson = '{"a": 123, "b": 456}'
    // 设置请求头
    req.setHeader('xx', 'aaa')
    
    req.write(postJson)
    req.end(); // 结束请求
    
    

    http、https、http2 开启服务的区别

    1. http
    const http = require('http')
    const options = {}
    // options 可不传
    http.createServer(options, (req, res) => {
      res.end()
    }).listen(3000)
    
    http.createServer((req, res) => {
      res.end()
    }).listen(3000)
    
    1. https
    const https = require('https')
    const fs = require('fs')
    
    const options = {
      key: fs.readFileSync('./privatekey.pem'), // 私钥
      cert: fs.readFileSync('./certificate.pem') // 公钥
    }
    
    https.createServer(options, (req, res) => {
      res.end()
    }).listen(3000)
    
    1. http2
    const http2 = require('http2')
    const fs = require('fs')
    
    const options = {
      key: fs.readFileSync('./privatekey.pem'), // 私钥
      cert: fs.readFileSync('./certificate.pem') // 公钥
    }
    
    http2.createSecureServer(options, (req, res) => {
      res.end()
    }).listen(3000)
    

    最后,关于 node 还有很多需要学的,比如 文件(fs)系统,及 node 使用数据库,还有框架(express、koa2,曾经学过,不用忘的好快),服务器部署等,加油!。

  • 相关阅读:
    vs2010中如何编译dll
    EM图解
    二级指针代替二维数组传入参数
    常見算法的穩定性
    Opencv +vs2010的问题之0x000007b
    Linux C程序设计大全之gdb学习
    makefile学习
    python之如何share你的module
    socket与http的区别
    最完美的单例实现
  • 原文地址:https://www.cnblogs.com/EnSnail/p/10960256.html
Copyright © 2011-2022 走看看