前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >node.js之koa2知识点总结

node.js之koa2知识点总结

作者头像
YungFan
发布2020-12-07 10:37:34
4130
发布2020-12-07 10:37:34
举报
文章被收录于专栏:学海无涯学海无涯

第一个程序

代码语言:javascript
复制
const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
    ctx.body = 'Hello Koa2'
})

app.listen(3000)
console.log('server is running at port 3000')

路由

简单路由

代码语言:javascript
复制
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')

// 路由
let router = new Router({
    // 前缀 
    prefix : '/nodejs'
})

router
    .get('/index', async ctx => {
    let html = '<a href="https://www.abc.edu.cn">商贸学院</li>'
    ctx.body = html
})

app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)
console.log('server is running at port 3000')

复杂路由

代码语言:javascript
复制
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')

// 子路由
let index = new Router()
index.get('/index', async ctx => {
    let html = '<a href="https://www.abc.edu.cn">商贸学院</li>'
    ctx.body = html
})

// 子路由
let error = new Router()
error.get('/error', async ctx => {
    let html = 'Error Page'
    ctx.body = html
})

// 装载路由
let router = new Router()
router.use(index.routes(), index.allowedMethods()) // 访问路径:/index
router.use('/koa2', error.routes(), error.allowedMethods()) // 访问路径:/koa2/error

app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)
console.log('server is running at port 3000')

get与post

判断

代码语言:javascript
复制
const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')

// 使用ctx.body解析中间件
app.use(bodyParser())

app.use(async ctx => {
    // GET请求
    if (ctx.url == '/' && ctx.method == 'GET') {
        let html = `
          <form method="POST" action="/">
            用户: <input name="username" /><br/>
            密码: <input name="password" type="password"/><br/>
            <input type="submit"/>
          </form>
            `
        ctx.body = html
    } 
    // POST请求
    else if (ctx.url == '/' && ctx.method == 'POST') {
        let postData = ctx.request.body
        ctx.body = postData
    } 
    else {
        ctx.body = '<h1>404 Page Not Found</h1>'
    }
})

app.listen(3000)
console.log('server is running at port 3000')

获取参数

代码语言:javascript
复制
const Koa = require('koa')
const app = new Koa()

app.use(async ctx => {
    // GET请求
    let url = ctx.url
    let ctx_query = ctx.query
    let ctx_querystring = ctx.querystring

    ctx.body = {
        url,
        ctx_query,
        ctx_querystring
    }
})

app.listen(3000)
console.log('server is running at port 3000')

静态资源

代码语言:javascript
复制
const Koa = require('koa')
const path = require('path')
const static = require('koa-static')

const app = new Koa()

// 静态资源目录对于相对入口文件的路径
const staticPath = './static'

app.use(static(
    path.join( __dirname,  staticPath)
))

app.use( async ctx => {
    let html = 'YungFan'
    ctx.body = html
})

// 访问:http://localhost:3000/iOSer.png  http://localhost:3000/style.css  http://localhost:3000/method.js

app.listen(3000)
console.log('server is running at port 3000')

文件上传

代码语言:javascript
复制
const Koa = require('koa')
const fs = require('fs')
const path = require('path')
const app = new Koa()
const Router = require('koa-router')
const koaBody = require('koa-body')

// koaBody 完成上传文件
app.use(koaBody({
    multipart: true,
    formidable: {
        maxFileSize: 5 * 1024 * 1024    // 设置上传文件大小最大限制,默认20M,这里设置为5M
    }
}))

app.use(async ctx => {
    // 单文件
    if (ctx.url == '/upload' && ctx.method == 'GET') {
        let html = `
          <form method="POST" action="/upload" enctype="multipart/form-data">
            <input type="file" name="file" id="file" value=""/><br/>
            <input type="submit"/>
          </form>
            `
        ctx.body = html
    }
    // 多文件
    else if (ctx.url == '/uploads' && ctx.method == 'GET') {
        let html = `
          <form method="POST" action="/uploads" enctype="multipart/form-data">
            <input type="file" name="file" id="file" value="" multiple="multiple" /><br/>
            <input type="submit"/>
          </form>
            `
        ctx.body = html
    }
    else if (ctx.url == '/upload' && ctx.method == 'POST') {
        // 上传单个文件
        const file = ctx.request.files.file // 获取上传文件
        // 创建可读流
        const reader = fs.createReadStream(file.path)
        // 上传路径
        let filePath = path.join(__dirname, 'upload/')
        // 检查路径是否存在
        checkDirExist(filePath)
        // 文件名
        const fileName = `${filePath}/${file.name}`
        // 创建可写流
        const upStream = fs.createWriteStream(fileName)
        // 可读流通过管道写入可写流
        reader.pipe(upStream)
        return ctx.body = "单文件上传成功!"
    }
    else if (ctx.url == '/uploads' && ctx.method == 'POST') {
        // 上传多个文件
        const files = ctx.request.files.file 
        for (let file of files) {
            // 里面操作和前面单文件一样
            const reader = fs.createReadStream(file.path)
            let filePath = path.join(__dirname, 'upload/')
            checkDirExist(filePath)
            const fileName = `${filePath}/${file.name}`
            const upStream = fs.createWriteStream(fileName)
            reader.pipe(upStream)
        }
        return ctx.body = "多文件上传成功!"
    }
    else {
        ctx.body = '<h1>404 Page Not Found</h1>'
    }
})

app.listen(3000)
console.log('server is running at port 3000')

// 判断文件夹是否存在,不存在则创建
function checkDirExist(path) {
    if (!fs.existsSync(path)) {
        fs.mkdirSync(path)
    }
}

mysql操作

封装mysql

代码语言:javascript
复制
const mysql = require('mysql')

let pools = {} // 连接池

let operation = (sql, host = '127.0.0.1') => {
    if (!pools.hasOwnProperty(host)) { // 是否存在连接池
        pools[host] = mysql.createPool({ // 不存在创建
            host: host,
            port: '3306',
            user: 'root',
            password: 'root',
            database: 'nodejsDB'
        })
    }

    return new Promise((resolve, reject) => {
        pools[host].getConnection((err, connection) => { // 初始化连接池
            if (err)
                console.log(err,'数据库连接失败')
            else
                connection.query(sql, (err, results) => { // 去数据库查询数据
                    connection.release() // 释放连接资源
                    if (err)
                        reject(err)
                    else
                        resolve(results)
            })
        })
    })
}

module.exports = operation

操作

代码语言:javascript
复制
const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const dbTool = require('./dbTools') // 注意路径

let router = new Router()

router.get('/users/list', async (ctx, next) => {
    await dbTool(`select * from t_user`).then((res) => {
        console.log(res)
        ctx.body = res // 返回给前端的数据
    })

    await next()
})

app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)
console.log('server is running at port 3000')
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 第一个程序
  • 路由
    • 简单路由
      • 复杂路由
      • get与post
        • 判断
          • 获取参数
          • 静态资源
          • 文件上传
          • mysql操作
            • 封装mysql
              • 操作
              相关产品与服务
              云数据库 SQL Server
              腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档