知新 | koa框架入门到熟练第二章

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 这里对koa-bodyparser的使用教程。

koa-bodyparser 使用

这里对koa-bodyparser的使用教程。

目录如下

ejs文件

ejs模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/doAdd" method="post">
    用户名: <input type="text" name="username"/>
    密码: <input type="password" name="password"/>
    <button type="submit">提交</button>
</form>
</body>
</html>

koa-bodyparser

使用koa-bodyparser获取body内容



var koa = require("koa");

var Router = require("koa-router");

var bodyParser = require("koa-bodyparser");

var app = new koa();

var router = new Router();

var views = require("koa-views");

app.use(views("views", {
    extension: "ejs",
}))

app.use(bodyParser());

// koa中间件
app.use(async (ctx, next) => {
    console.log(new Date());

    await next();
});



router.get("/", async (ctx) => {
    await ctx.render("index");
})

router.post("/doAdd", async (ctx) => {
    console.log(ctx.request.body);
    ctx.body = ctx.request.body;
})
app.use(router.routes());
app.use(router.allowedMethods());


app.listen(3001);

使用效果

登录页面

koa-static

这里学习使用koa-static

安装

PS C:\Users\Administrator\Desktop\untitled3> npm install --save koa-static
npm WARN untitled3@1.0.0 No description
npm WARN untitled3@1.0.0 No repository field.

+ koa-static@5.0.0
added 1 package in 2.042s

2 packages are looking for funding
  run `npm fund` for details

PS C:\Users\Administrator\Desktop\untitled3>

访问效果

访问效果如下

art-template

这里使用art-template 作为一个模板引擎使用

安装

PS C:\Users\Administrator\Desktop\untitled3> npm install --save art-template
npm WARN untitled3@1.0.0 No description
npm WARN untitled3@1.0.0 No repository field.

+ art-template@4.13.2
added 33 packages from 141 contributors in 6.704s

2 packages are looking for funding
  run `npm fund` for details

PS C:\Users\Administrator\Desktop\untitled3> npm install --save koa-art-template
npm WARN untitled3@1.0.0 No description
npm WARN untitled3@1.0.0 No repository field.

+ koa-art-template@1.1.1
added 2 packages from 4 contributors in 2.336s

2 packages are looking for funding
  run `npm fund` for details

代码如下



var koa = require("koa");

var Router = require("koa-router");

var bodyParser = require("koa-bodyparser");

var static = require("koa-static");

var app = new koa();

var router = new Router();

var views = require("koa-views");

var render = require("koa-art-template");

var path = require("path");

app.use(views("views", {
    extension: "ejs",
}))

app.use(static("./static"));

app.use(bodyParser());

// koa中间件
app.use(async (ctx, next) => {
    console.log(new Date());

    await next();
});



router.get("/", async (ctx) => {
    await ctx.render("index");
})

router.post("/doAdd", async (ctx) => {
    console.log(ctx.request.body);
    ctx.body = ctx.request.body;
})

render(app, {
    root: path.join(__dirname, "views"),
    extname: ".art",
})

app.use(async function (ctx){
    await ctx.render("user");
})

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


app.listen(3001);

art 文件如下



var koa = require("koa");

var Router = require("koa-router");

var bodyParser = require("koa-bodyparser");

var static = require("koa-static");

var app = new koa();

var router = new Router();

var views = require("koa-views");

var render = require("koa-art-template");

var path = require("path");

app.use(views("views", {
    extension: "ejs",
}))

app.use(static("./static"));

app.use(bodyParser());

// koa中间件
app.use(async (ctx, next) => {
    console.log(new Date());

    await next();
});



router.get("/", async (ctx) => {
    await ctx.render("index");
})

router.post("/doAdd", async (ctx) => {
    console.log(ctx.request.body);
    ctx.body = ctx.request.body;
})

render(app, {
    root: path.join(__dirname, "views"),
    extname: ".art",
})

app.use(async function (ctx){
    await ctx.render("user");
})

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


app.listen(3001);

访问效果

cookie



var koa = require("koa");

var Router = require("koa-router");

var bodyParser = require("koa-bodyparser");

var static = require("koa-static");

var app = new koa();

var router = new Router();

var views = require("koa-views");

var render = require("koa-art-template");

var path = require("path");


app.use(bodyParser());

// koa中间件
app.use(async (ctx, next) => {
    console.log(new Date());

    await next();
});

router.get("/", async (ctx) => {
    ctx.cookies.set("ming", "ming")
})
app.use(router.routes());
app.use(router.allowedMethods());


app.listen(3001);

koa-session

PS C:\Users\Administrator\Desktop\untitled3> npm install koa-session
npm WARN untitled3@1.0.0 No description
npm WARN untitled3@1.0.0 No repository field.

+ koa-session@6.0.0
added 10 packages from 14 contributors in 3.484s

2 packages are looking for funding
  run `npm fund` for details

PS C:\Users\Administrator\Desktop\untitled3>

编写一个简单的刷新页面次数增加



var koa = require("koa");

var Router = require("koa-router");

var bodyParser = require("koa-bodyparser");

var static = require("koa-static");

var app = new koa();

var router = new Router();

var views = require("koa-views");

var render = require("koa-art-template");

var path = require("path");

var session = require("koa-session");

app.keys = ['secret'];   // session加密字段

app.use(session({
    key: 'koa:sess', //cookie key (default is koa:sess)
    maxAge: 86400000, // cookie的过期时间 maxAge in ms (default is 1 days)
    overwrite: true, //是否可以overwrite    (默认default true)
    httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
    signed: true, //签名默认true
    rolling: false, //在每次请求时强行设置cookie,这将重置cookie过期时间(默认:false)
    renew: false, //(boolean) renew session when session is nearly expired,
}, app));

app.use(bodyParser());

// koa中间件
app.use(async (ctx, next) => {
    console.log(new Date());

    await next();
});


app.use(ctx => {
    // ignore favicon
    if (ctx.path === '/favicon.ico') return
    console.log(ctx.session)
    let n = ctx.session.views || 0
    ctx.session.views = ++n
    ctx.body = n + ' views'
});


router.get("/", async (ctx) => {
    ctx.cookies.set("ming", "ming")
})

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


app.listen(3001);

原型链继承

// 构造原型
function Person(name, age) {
    this.name = name;
    this.age = 333;
    this.run = function () {
        console.log(this.name, this.age)
    }
}

// 添加work方法,在原型链上继承
Person.prototype.work = () => {
    console.log("work");
}

function Web() {

}

// 同样继承
Web.prototype = new Person();

var w = new Web();
// 以下两个运行原型链的值
w.run();
w.work()

静态方法和构造方法

// 新建类
class Person{
    constructor(name) {
        this._name = name;
    }
    run(){
        console.log(this._name);
    }
    // 静态方法
    static work(){
        console.log("静态方法");
    }
}

Person.work();

koa 操作mongoDB

安装相关的库


PS C:\Users\Administrator\Desktop\untitled3> npm install mongodb --save
npm WARN untitled3@1.0.0 No description
npm WARN untitled3@1.0.0 No repository field.

+ mongodb@3.5.9
updated 1 package in 2.854s

2 packages are looking for funding
  run `npm fund` for details

PS C:\Users\Administrator\Desktop\untitled3>

增加一条数据



var MongoClient = require("mongodb").MongoClient;

var dbUrl = 'mongodb://106.53.115.12:27017/'

var dbName = "koa";

// 连接
MongoClient.connect(dbUrl, (err, client) => {
    if(err){
        console.log(err);
        return;
    }

    var db = client.db(dbName);

    // 增加数据
    db.collection("user").insertOne({
        "username":"xiaoxiao","age":"23"
    });

})

结果:

对返回结果进行处理



var MongoClient = require("mongodb").MongoClient;

var dbUrl = 'mongodb://106.53.115.12:27017/'

var dbName = "koa";

// 连接
MongoClient.connect(dbUrl, (err, client) => {
    if(err){
        console.log(err);
        return;
    }

    var db = client.db(dbName);

    // 增加数据
    db.collection("user").insertOne({
        "username":"xiaoxiao","age":"23"
    }, function (err, result) {
        if(!err){
            console.log("增加数据成功 ");
            client.close();
            console.timeEnd("start");
        }
    });

})

查询数据

代码如下



var MongoClient = require("mongodb").MongoClient;

var dbUrl = 'mongodb://106.53.115.12:27017/'

var dbName = "koa";

// 连接
MongoClient.connect(dbUrl, (err, client) => {
    if(err){
        console.log(err);
        return;
    }

    var db = client.db(dbName);

    var result = db.collection("user").find(0);

    result.toArray((err, docs) => {
        console.log(docs);
    })

})

输出内容如下

"C:\Program Files\nodejs\node.exe" C:\Users\Administrator\Desktop\untitled3\01es6.js
(node:15216) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[
  { _id: 5f0fe666bc0d9e41101dffd3, username: 'xiaoxiao', age: '23' },
  { _id: 5f0fe7f4949f1b420c120fe7, username: 'xiaoxiao', age: '23' }
]

koa 应用生成器

全局安装

使用全局安装koa的脚手架

PS C:\Users\Administrator\Desktop\untitled3> npm install koa-generator -g
npm WARN deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
C:\Users\Administrator\AppData\Roaming\npm\koa -> C:\Users\Administrator\AppData\Roaming\npm\node_modules\koa-generator\bin\koa
C:\Users\Administrator\AppData\Roaming\npm\koa2 -> C:\Users\Administrator\AppData\Roaming\npm\node_modules\koa-generator\bin\koa2
+ koa-generator@1.1.17
updated 1 package in 0.905s
PS C:\Users\Administrator\Desktop\untitled3>

创建项目

PS C:\Users\Administrator\Desktop> ls


    目录: C:\Users\Administrator\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        2020/7/14     17:08                insurv-mina-node-api
d-----        2020/7/14     17:45                koa
d-----        2020/7/14     17:55                untitled
d-----        2020/7/16     14:16                untitled3
-a----        2020/7/16     12:04        5782870 Navicat Premium 15.x最新注册机.zip
-a----        2020/7/14     17:07           1428 Visual Studio Code.lnk
-a----       2019/11/30     18:03           1526 WPS 2019.lnk
-a----        2020/7/14     18:52           1064 百度网盘.lnk


PS C:\Users\Administrator\Desktop> mkdir ./ming


    目录: C:\Users\Administrator\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        2020/7/16     14:19                ming


PS C:\Users\Administrator\Desktop> ls


    目录: C:\Users\Administrator\Desktop


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        2020/7/14     17:08                insurv-mina-node-api
d-----        2020/7/14     17:45                koa
d-----        2020/7/16     14:19                ming
d-----        2020/7/14     17:55                untitled
d-----        2020/7/16     14:16                untitled3
-a----        2020/7/16     12:04        5782870 Navicat Premium 15.x最新注册机.zip
-a----        2020/7/14     17:07           1428 Visual Studio Code.lnk
-a----       2019/11/30     18:03           1526 WPS 2019.lnk
-a----        2020/7/14     18:52           1064 百度网盘.lnk


PS C:\Users\Administrator\Desktop> cd ./ming
PS C:\Users\Administrator\Desktop\ming> ls
PS C:\Users\Administrator\Desktop\ming> koa koa_demo

   create : koa_demo
   create : koa_demo/package.json
   create : koa_demo/app.js
   create : koa_demo/public
   create : koa_demo/routes
   create : koa_demo/routes/index.js
   create : koa_demo/routes/users.js
   create : koa_demo/public/javascripts
   create : koa_demo/views
   create : koa_demo/views/index.jade
   create : koa_demo/views/layout.jade
   create : koa_demo/views/error.jade
   create : koa_demo/public/images
   create : koa_demo/public/stylesheets
   create : koa_demo/public/stylesheets/style.css
   create : koa_demo/bin
   create : koa_demo/bin/www

   install dependencies:
     > cd koa_demo && npm install

   run the app:
     > SET DEBUG=koa_demo:* & npm start

PS C:\Users\Administrator\Desktop\ming> ls


    目录: C:\Users\Administrator\Desktop\ming


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        2020/7/16     14:19                koa_demo


PS C:\Users\Administrator\Desktop\ming> cd ./koa_demo
PS C:\Users\Administrator\Desktop\ming\koa_demo>

此时脚手架已经安装成功

安装依赖

PS C:\Users\Administrator\Desktop\ming\koa_demo> npm install
npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated swig@1.4.2: This package is no longer maintained
npm WARN deprecated jade@1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm WARN deprecated constantinople@3.0.2: Please update to at least constantinople 3.1.1
npm WARN deprecated transformers@2.1.0: Deprecated, use jstransformer
npm WARN deprecated native-or-bluebird@1.2.0: 'native-or-bluebird' is deprecated. Please use 'any-promise' instead.

> nodemon@1.19.4 postinstall C:\Users\Administrator\Desktop\ming\koa_demo\node_modules\nodemon
> node bin/postinstall || exit 0

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

added 367 packages from 208 contributors in 21.748s

1 package is looking for funding
  run `npm fund` for details

PS C:\Users\Administrator\Desktop\ming\koa_demo>

启动项目

npm start
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
中间件 PHP 数据安全/隐私保护
【Thinkphp 6】框架基础知识
【Thinkphp 6】框架基础知识
186 1
|
5月前
|
JSON 中间件 数据处理
实践出真知:通过项目学习Python Web框架的路由与中间件设计
【7月更文挑战第19天】探索Python Web开发,掌握Flask或Django的关键在于理解路由和中间件。路由连接URL与功能,如Flask中@app.route()定义请求响应路径。中间件在请求处理前后执行,提供扩展功能,如日志、认证。通过实践项目,不仅学习理论,还能提升构建高效Web应用的能力。示例代码展示路由定义及模拟中间件行为,强调动手实践的重要性。
60 1
|
JavaScript 前端开发 API
Vue.js入门指南:从基础到进阶,掌握现代JavaScript框架的核心概念与高级特性(2W字小白教程)
Vue.js入门指南:从基础到进阶,掌握现代JavaScript框架的核心概念与高级特性(2W字小白教程)
181 0
|
SQL 前端开发 Shell
Django框架入门
Django框架入门
227 0
|
存储 设计模式 JavaScript
前端知识库Reactjs基础系列二(进阶)
上一节复习reactjs的基础知识,本节主要了解reactjs中一些高阶用法。
|
JavaScript 前端开发
前端学习案例-Redux入门教学
前端学习案例-Redux入门教学
77 0
前端学习案例-Redux入门教学
|
JSON JavaScript 前端开发
koa框架学习记录(3)
一个前端学习koa的简单记录
|
前端开发
koa框架学习记录(5)
一个前端学习koa的简单记录
|
前端开发 中间件
koa框架学习记录(4)
一个前端学习koa的简单记录
|
JavaScript 前端开发 中间件
koa框架学习记录(6)
一个前端学习koa的简单记录