node http 模塊 經常使用知識點記錄

關於 node,老是斷斷續續的學一點,也只能在本地本身模擬實戰,相信總會有實戰的一天~~html

  • http 做爲服務端,開啓服務,處理路由,響應等
  • http 做爲客戶端,發送請求
  • http、https、http2 開啓服務

做爲服務端

  1. 開啓服務,有兩種方式

方式1node

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. 路由

路由的原理:根據路徑去判斷express

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,曾經學過,不用忘的好快),服務器部署等,加油!。json

相關文章
相關標籤/搜索