关于java:知新-koa框架入门到熟练第二章

43次阅读

共计 10972 个字符,预计需要花费 28 分钟才能阅读完成。

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

微信公众号

正文完
 0