前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >知新 | koa框架入门到熟练第二章

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

原创
作者头像
mySoul
修改2020-07-20 09:57:39
6510
修改2020-07-20 09:57:39
举报
文章被收录于专栏:mySoul

koa-bodyparser 使用

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

目录如下

ejs文件

ejs模板文件

代码语言:txt
复制
<!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内容

代码语言:txt
复制
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

安装

代码语言:txt
复制
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 作为一个模板引擎使用

安装

代码语言:txt
复制
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

代码如下

代码语言:txt
复制
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 文件如下

代码语言:txt
复制
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

代码语言:txt
复制
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

代码语言:txt
复制
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>

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

代码语言:txt
复制
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);

原型链继承

代码语言:txt
复制
// 构造原型
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()

静态方法和构造方法

代码语言:txt
复制
// 新建类
class Person{
    constructor(name) {
        this._name = name;
    }
    run(){
        console.log(this._name);
    }
    // 静态方法
    static work(){
        console.log("静态方法");
    }
}

Person.work();

koa 操作mongoDB

安装相关的库

代码语言:txt
复制
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>

增加一条数据

代码语言:txt
复制
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"
    });

})

结果:

对返回结果进行处理

代码语言:txt
复制
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");
        }
    });

})

查询数据

代码如下

代码语言:txt
复制
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);
    })

})

输出内容如下

代码语言:txt
复制
"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的脚手架

代码语言:txt
复制
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>

创建项目

代码语言:txt
复制
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>

此时脚手架已经安装成功

安装依赖

代码语言:txt
复制
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>

启动项目

代码语言:txt
复制
npm start

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • koa-bodyparser 使用
    • ejs文件
      • koa-bodyparser
        • 使用效果
        • koa-static
          • 安装
            • 访问效果
            • art-template
              • 安装
                • 代码如下
                  • art 文件如下
                    • 访问效果
                    • cookie
                    • koa-session
                      • 编写一个简单的刷新页面次数增加
                      • 原型链继承
                      • 静态方法和构造方法
                      • koa 操作mongoDB
                        • 增加一条数据
                          • 对返回结果进行处理
                            • 查询数据
                            • koa 应用生成器
                              • 全局安装
                                • 创建项目
                                  • 安装依赖
                                    • 启动项目
                                    相关产品与服务
                                    消息队列
                                    腾讯云消息队列 TDMQ 是分布式架构中的重要组件,提供异步通信的基础能力,通过应用解耦降低系统复杂度,提升系统可用性和可扩展性。TDMQ 产品系列提供丰富的产品形态,包含 CKafka、RocketMQ、RabbitMQ、Pulsar、CMQ 五大产品,覆盖在线和离线场景,满足金融、互联网、教育、物流、能源等不同行业和场景的需求。
                                    领券
                                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档