zoukankan      html  css  js  c++  java
  • Koa2

    安装

    yarn add koa

    代码

    Koa的核心代码就三行

    const app = new Koa()
    app.use(middleware)
    app.listen(3000)
    const Koa = require('koa')
    const app = new Koa()
    
    app.use(async (ctx, next) => {
      ctx.body = 'Hello World!'
    })
    
    app.listen(8080)

    至此一个简单的服务器运行成功。

    koa脚手架

    npm install -g koa2-generator

    koa2 koa-demo

    编写一个静态页面

    module.exports = `
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Koa Server HTMl</title>
          <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet">
          <script src="https://cdn.bootcss.com/jquery/3.2.0/jquery.min.js"></script>
          <script src="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.min.js"></script>
        </head>
        <body>
          <div class="container">
            <div class="row">
              <div class="col-md-8">
                <h1>Hi Susan</h1>
                <p>This is a test</p>
              </div>
              <div class="col-md-4">
                <p>测试静态 HTML 页面</p>
              </div>
            </div>
          </div>
        </body>
      </html>
    
    `
    View Code
    const Koa = require('koa')
    const app = new Koa()
    
    const {normal} = require('./tpl/index')
    
    app.use(async(ctx, next) => {
      ctx.type = 'text/html;charset=utf-8;'
      ctx.body =  normal
    })
    
    app.listen(8080)
    View Code

    编写模板页面

    安装pug模板引擎

    yarn add pug

    动态模板引擎代码

    module.exports = `
    doctype html
    html
      head
        meta(charset='utf-8')
        meta(name='viewport=', content='width=device-width, initail-scale=1')
        title Koa Server Pug
        link(href='https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css',rel='stylesheet')
        script(src='https://cdn.bootcss.com/jquery/3.2.0/jquery.min.js')
        script(src='https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.min.js')
      body
        .container
          .row
            .col-md-8
              h1 Hi #{ name }
              p This is a test
            .col-md-4
              p 测试动态PUG模板引擎
    
    `
    View Code

    js代码

    const Koa = require('koa')
    const app = new Koa()
    
    const pug = require('pug')
    
    const {pugTpl} = require('./tpl/index')
    
    app.use(async(ctx, next) => {
      ctx.type = 'text/html;charset=utf-8;'
      ctx.body =  pug.render(pugTpl, {
        name: 'Susan'
      })
    })
    
    app.listen(8080)
    View Code

    使用模板引擎中间件,支持ejs,pug

    koa-views

    pug模板引擎代码

    doctype html
    html
      head
        meta(charset='utf-8')
        meta(name='viewport=', content='width=device-width, initail-scale=1')
        title Koa Server Pug
        link(href='https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css',rel='stylesheet')
        script(src='https://cdn.bootcss.com/jquery/3.2.0/jquery.min.js')
        script(src='https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.min.js')
      body
        .container
          .row
            .col-md-8
              h1 Hi #{ name }
              p This is a test
            .col-md-4
              p 测试动态PUG模板引擎
    View Code

    js代码

    const Koa = require('koa')
    const app = new Koa()
    const views = require('koa-views')
    const {resolve} = require('path')
    
    app.use(views(resolve(__dirname, './views'), {
      extension: 'pug'
    }))
    
    app.use(async(ctx, next) => {
      await ctx.render('index', {
        name: 'Susan'
      })
    })
    
    app.listen(8080, () => {
      console.log('http://localhost:8080')
    })
    View Code

    koa-router

    yarn add koa-router

    代码

    const router = require('koa-router')()
    
    router.get('/news', async (ctx, next) => {
      ctx.body  = '路由'
    })
    
    router.get('/news/:id', async (ctx, next) => {
      ctx.body = '动态路由'
    })
    
    app.use(router.routes())
    View Code

    路由分离

    代码

    const router = require('koa-router')()
    
    router.prefix('/user')
    
    router.get('/', async ctx => {
      ctx.body = 'Hello Koa2'
    })
    
    router.get('/info', async ctx => {
      ctx.body = 'Hello UserInfo'
    })
    
    module.exports = router
    View Code
    const user = require('./routes/user')
    
    app.use(user.routes()).use(user.allowedMethods())
    View Code

    GET

    通过ctx.query/ctx.querystring/ctx.request.query/ctx.request.querystring

    代码

    router.get('/news', async (ctx, next) => {
      console.log('ctx.query', ctx.query)
      console.log('ctx.querystring', ctx.querystring)
      console.log('ctx.request.query', ctx.request.query)
      console.log('ctx.request.querystring', ctx.request.querystring)
    })
    View Code
    curl i http://localhost:3000/news?name='Susan&age=12'

    POST

    通过koa-body

    const koaBody = require('koa-body')
    
    app.use(koaBody())
    
    router.post('/doAction', async ctx => {
      console.log('ctx.request.body', ctx.request.body)
    })
    View Code
    curl i http://localhost:3000/doAction -d 'name=Susan,age=20'

    静态资源

    安装koa-static

    代码

    const server = require('koa-static')
    
    app.use(server(resolve(__dirname, './static')))
    
    router.get('/', async ctx => {
      await ctx.render('index')
    })
    View Code
    <link href="css/style.css" rel="stylesheet" />
    
    <img src="img/1.jpg"/>
    
    <script src="js/index.js"></script>
    View Code

    Cookie

    ctx.cookies.set(name, value, [options])
    
    ctx.cookies.get(name)

    如何处理中文

    使用Buffer转换

    // 将中文转换base64字符串
    new Buffer(value).toString('base64')
    // 将base64字符串转换为中文
    new Buffer(value, 'base64').toString()

    Session

    安装koa-session

    const session = require('koa-session')
    
    app.keys = ['some secret hurr']
    const CONFIG = {
      key: 'koa:sess', 
      maxAge: 86400000,
      autoCommit: true, 
      overwrite: true, 
      httpOnly: true, 
      signed: true, 
      rolling: false, 
      renew: false
    }
    
    app.use(session(CONFIG, app))
    
    router.get('/', async ctx => {
      let n = ctx.session.view || 0
      ctx.session.view = ++ n
      ctx.body = n
    })
    View Code

    Mongodb 

     https://www.mongodb.com/download-center?jmp=nav#community

    操作数据库

    http://mongodb.github.io/node-mongodb-native/ 

    安装mongodb

    连接数据库,创建集合,插入数据

    const MongoClient = require('mongodb').MongoClient
    const url = 'mongodb://127.0.0.1:27017'  // URL
    const dbName = 'dbs' // 数据库名称
    const client = new MongoClient(url)  // 创建一个Mongodb Client
    
    client.connect(err=>{ // 连接数据库
      if (err) return 
      console.log('Connected successfully to server')
      const db = client.db(dbName) 
      // 插入数据
      db.collection('documents').insertMany([
        {a:1},
        {b:2},
        {c:3}
      ])
      db.collection('documents').insertOne(
        {d:4}
      )
      client.close()
    }) 
    View Code

    查找数据

    db.collection('documents').find({})
      .toArray((err, docs) => {
        if (err) return 
        console.log(docs)
      })

    更新数据

    db.collection('documents')
      .updateOne({a:1}, {$set: {a: 100}}, (err, res) => {
        if (err) return 
        console.log(res)
      })
    
    db.collection('documents')
      .updateMany({a:1}, {$set: {a: 100}}, (err, res) => {
        if (err) return 
        console.log(res)
      })

    删除数据

    db.collection('documents')
      .deleteOne({a:10}, (err, res) => {
        if (err) return 
        console.log(res)
      })

    Robo 3T

    https://robomongo.org/

    Mongoose

    https://mongoosejs.com/docs/api.html

    连接数据库

    首先配置数据库,创建一个dbs的数据库

    module.exports = {
      dbs:'mongodb://127.0.0.1:27017/dbs'
    }

    数据库创建完毕,那么创建model也就是集合,即表

    const mongoose = require('mongoose') 
    
    let personSchema = new mongoose.Schema({
      name: String,
      age: Number
    })
    
    module.exports = mongoose.model('Person', personSchema)

    数据库和表创建完毕,那么开始连接数据库

    const mongoose = require('mongoose')
    const dbConfig = require('./dbs/config')
    mongoose.connect(dbConfig.dbs, { useNewUrlParser: true })

    此刻数据库连接成功,那么我们开始

    添加数据

    router.post('/addPerson', async ctx => {
      const person = new Person({
        name: ctx.request.body.name,
        age: ctx.request.body.age
      })
      let code
      try {
        await person.save()
        code = 0
      } catch (error) {
        code = 1
      }
      ctx.body = {
        code
      }
    })

    查询数据

    const res = await Person.findOne({name:ctx.request.body.name})
    const ress = await Person.find({name: ctx.request.body.name})

    更新数据

    const result = await Person.where({
      name: ctx.request.body.name
    }).update({
      age:ctx.request.body.age
    })

    删除数据

    const result = await Person.where({
      name: ctx.request.body.name
    }).remove()

    Redis

    访问网页服务器端会在客户端设置cookie保存session

    每次请求把cookie中session发送到服务器端

    服务端用session保存客户端状态

    服务器端会把session的值保存到Redis中

    浏览器用cookie保存session

    而且Redis是一个非常快速的读写数据库

    案例:登录校验

    安装

    https://github.com/MicrosoftArchive/redis/releases

    启动Redis

    安装koa中间件操作Redis

    yarn add koa-generic-session koa-redis

    连接Redis

    app.keys=['keys','keyskeys'] // session加密处理,随便两个值
    app.use(session({
      key:'mt',
      prefix:'mtpr',
      store: new Redis(),
    }))

    使用session

    ctx.session.count++

    我们也可以直接对Redis操作

    const Store = new Redis().client
    const st = await Store.hset('fix', 'name', Math.random())

    使用redis-cli.exe查看数据

    key *

    get 

    hset

    hget

  • 相关阅读:
    docker使用阿里云Docker镜像库加速
    FastDFS文件系统(二) fastdfs和其他文件系统区别
    CentOS7—HAProxy安装与配置
    安装完CentOS 7 后必做的七件事
    让一个端口同时做两件事:http/https和ssh
    Hyper-v之利用差异磁盘快速创建多个虚拟机
    MySQL5.7安装与配置(YUM)
    CentOS7 配置阿里云yum源
    60款顶级大数据开源工具
    ubuntu设置分辨率
  • 原文地址:https://www.cnblogs.com/sonwrain/p/10590571.html
Copyright © 2011-2022 走看看