zoukankan      html  css  js  c++  java
  • nodejs(7)练习 http 和 express 创建简单的服务器

    http 

    const http = require('http')
    
    // 创建服务器
    const server = http.createServer()
    
    // 绑定事件,监听客户端的请求
    server.on('request', (req, res) => {
        // 写入响应头,防止中文乱码
        res.writeHeader(200, {
          'Content-Type': 'text/html; charset=utf-8'
        })
      res.end('你好 http 服务器!')
    })
    
    server.listen(3333, () => {
      console.log('http server running at http://127.0.0.1:3333')
    })

    express 

    const express = require('express')
    
    // 创建服务器
    const app = express()
    
    // 监听客户端的请求
    // 只有客户端的请求类型是 get,并且 请求地址是 / 根路径的时候,
    // 才会调用 后面指定的处理函数
    app.get('/', (req, res) => {
      // express 中,封装了更好用的 res.send 方法
      res.send('你好,express 服务器!')
    })
    
    // 监听客户端的post请求,并且请求的地址是 /adduser 的时候,
    // 才会调用后面指定的处理函数
    app.post('/adduser', (req, res) => {
      res.send('服务器处理成功!')
    })
    
    // 启动服务器
    app.listen(4444, () => {
      console.log('express server running at http://127.0.0.1:4444')
    })

    在express框架中获取客户端提交的表单数据

    const express = require('express')
    const qs = require('querystring')
    
    const app = express()
    
    // 监听客户端的 post 请求,且请求地址为 /adduser 的时候,会调用指定的处理函数
    app.post('/adduser', (req, res) => {
      // 注意:客户端提交到服务器的数据,都保存到了 req 请求对象中
      // 只要客户端向服务器通过post方式,提交了表单,那么 就会触发 req 的 data 事件
      // 只要安装一个 第三方的npm包,名字叫做 body-parser, 并进行简单配置,就能够直接使用 req.body获取到表单数据了
      let str = ''
      req.on('data', chunk => {
        // 把每次得到的分片数据,拼接到 str 字符串中
        // 如果 字符串 和 Buffer 数据进行拼接,得到结果,是字符串
        str += chunk
        // 思考:只要触发了 data,就证明有数据发送到服务器了,但是,什么时候,就证明数据已经发送和接收完毕了呢???
      })
    
      // 通过监听 req 的 end 事件,就能够直到数据已经发送完毕了,服务器也已经接收到了完整的数据!
      req.on('end', () => {
        // console.log(str)
        // 对数据进行 URL 解码操作
        // const strDecode = decodeURI(str)
        // console.log(strDecode)
        const result = qs.parse(str)
        // 使用 express 的 send 方法,向客户端发送 对象
        res.send(result)
      })
    
      // res.send('添加用户成功!')
    })
    
    app.listen(4444, () => {
      console.log('express server running at http://127.0.0.1:4444')
    })

     使用body-parser包解析表单数据

    安包:npm install body-parser -S

    const express = require('express')
    // 1. 导入 解析表单数据的包
    const bodyParser = require('body-parser')
    
    const app = express()
    // 2. 配置一下
    app.use(bodyParser.urlencoded({ extended: false }))
    
    app.post('/adduser', (req, res) => {
      console.log(req.body)
      res.send('ok')
    })
    
    app.listen(4444, () => {
      console.log('启动成功!')
    }) 
  • 相关阅读:
    23种设计模式
    设计模式中类的关系
    简单工厂模式
    SQL正则表达式
    C#中各种计时器
    C# List 排序
    常见名词解释
    PetaPoco入门
    jQuery UI Dialog
    c# winform 获取当前程序运行根目录
  • 原文地址:https://www.cnblogs.com/houfee/p/10287853.html
Copyright © 2011-2022 走看看