Web 服务器

  • 来源:Node.js实战第4章
  • Node内置的http功能适合用来开发HTTP功能,尽管它的API比较底层,没有“糖”的效果,但这一切都是为了
  • 高效简洁灵活
  • 先学习使用http功能开发
  • 再学习使用中间件添加功能
  • 然后学习使用Express加快开发效率

一些概念

中间件

  • 中间件一般为一个JavaScript函数,一般接受三个参数:请求对象、响应对象、命名为next的回调参数
  • 中间件是受到 Ruby Rack框架的启发
  • 中间件:小巧、自包含、可重用

http模块初使用

  • 如下是一个简单的http模块搭建的web server服务器
  • 使用createServer创建一个服务,并让它监听7890端口
  • 使用setHeader往响应中写入头部信息,一般来说,在响应中放入不同的响应头,以便客户端根据不同格式的响应头进行处理
const http = require('http')
const port = 7890

const server = http.createServer((req, res) => {
  const body = 'hello'
  res.setHeader('Content-Length', body.length)
  res.setHeader('Content-Type', 'text/plain')
  res.write(body)
  res.end()
})

server.listen(port)

创建302 404服务

  • 通过setHeader方法,能快速创建302 404的响应
// 302 跳转
  const url = 'https://baidu.com'

  res.setHeader('Location', url)
  res.statusCode = 302

  res.end()

// 404 Not Found
  res.statusCode = 404
  res.end()

创建Restful Api服务:post get

  • 这里只举例 post get 方法,其他如像 option put delete 请自行参考其他
  switch (req.method) {   // 判断当前的请求方法 
    case 'POST':
      req.setEncoding('utf-8')  // post带参时,使用 encoding utf-8 避免乱码的情况
      let item
      req.on('data', chunk => {
        item += chunk         // post 取参是个连续的过程
      })
      req.on('end', () => {
        console.log(item)     // rep.on'end' 时取出整个参数
        res.end('ok')
      })
      break

    case 'GET':
      const body = `hello`
      res.setHeader('Content-Length', Buffer.byteLength(body))        // 使用 Buffer 而不是 .length,避免不同字符带来的字节长度不同
      res.setHeader('Content-Type', 'text/plain; charset="utf-8"')

      res.end(body)   // res.write/res.end 的简写
      break
  }

利用 http 模块发起 http request

const http = require('http')
const options = {
  host: 'localhost',
  port: '7890',
  path: '/index.html'
}

const req = http.request(options, rep => {
  let body = ''
  rep.on('data', data => {
    body += data
  })
  rep.on('end', () => {
    console.log(body)
  })
})
req.end()

results matching ""

    No results matching ""