前端集散地|知新 | koa框架入门到熟练第二章

koa-bodyparser 使用 这里对koa-bodyparser的使用教程。
目录如下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Madk1tVn-1594993443999)(https://www.iming.info/wp-content/uploads/2020/07/wp_editor_md_211ccaf408f127f491c28c16e945e4cd.jpg)]
ejs文件 ejs模板文件

Title - 锐客网
用户名: 密码:

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框架入门到熟练第二章
文章图片

登录页面
前端集散地|知新 | koa框架入门到熟练第二章
文章图片

前端集散地|知新 | koa框架入门到熟练第二章
文章图片

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.042s2 packages are looking for funding run `npm fund` for detailsPS C:\Users\Administrator\Desktop\untitled3>

访问效果 访问效果如下
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rz9TdCsE-1594993444027)(https://www.iming.info/wp-content/uploads/2020/07/wp_editor_md_a86267852d172a96ee3958cb42f3e1c8.jpg)]
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.704s2 packages are looking for funding run `npm fund` for detailsPS 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.336s2 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);

访问效果 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xO5Dw4Mw-1594993444030)(https://www.iming.info/wp-content/uploads/2020/07/wp_editor_md_f50791cd5ce59ac2c36a5334fceb8b2c.jpg)]
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框架入门到熟练第二章
文章图片

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.484s2 packages are looking for funding run `npm fund` for detailsPS 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);

前端集散地|知新 | koa框架入门到熟练第二章
文章图片

原型链继承
// 构造原型 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();

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tzKR9GAh-1594993444043)(https://www.iming.info/wp-content/uploads/2020/07/wp_editor_md_905933f7ff23a1ef4c334186f6c69a75.jpg)]
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.854s2 packages are looking for funding run `npm fund` for detailsPS 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" }); })

结果:
前端集散地|知新 | koa框架入门到熟练第二章
文章图片

对返回结果进行处理
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); })})

【前端集散地|知新 | koa框架入门到熟练第二章】输出内容如下
"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\DesktopModeLastWriteTimeLength Name ----------------------- ---- d-----2020/7/1417:08insurv-mina-node-api d-----2020/7/1417:45koa d-----2020/7/1417:55untitled d-----2020/7/1614:16untitled3 -a----2020/7/1612:045782870 Navicat Premium 15.x最新注册机.zip -a----2020/7/1417:071428 Visual Studio Code.lnk -a----2019/11/3018:031526 WPS 2019.lnk -a----2020/7/1418:521064 百度网盘.lnkPS C:\Users\Administrator\Desktop> mkdir ./ming目录: C:\Users\Administrator\DesktopModeLastWriteTimeLength Name ----------------------- ---- d-----2020/7/1614:19mingPS C:\Users\Administrator\Desktop> ls目录: C:\Users\Administrator\DesktopModeLastWriteTimeLength Name ----------------------- ---- d-----2020/7/1417:08insurv-mina-node-api d-----2020/7/1417:45koa d-----2020/7/1614:19ming d-----2020/7/1417:55untitled d-----2020/7/1614:16untitled3 -a----2020/7/1612:045782870 Navicat Premium 15.x最新注册机.zip -a----2020/7/1417:071428 Visual Studio Code.lnk -a----2019/11/3018:031526 WPS 2019.lnk -a----2020/7/1418:521064 百度网盘.lnkPS C:\Users\Administrator\Desktop> cd ./ming PS C:\Users\Administrator\Desktop\ming> ls PS C:\Users\Administrator\Desktop\ming> koa koa_democreate : 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/wwwinstall dependencies: > cd koa_demo && npm installrun the app: > SET DEBUG=koa_demo:* & npm startPS C:\Users\Administrator\Desktop\ming> ls目录: C:\Users\Administrator\Desktop\mingModeLastWriteTimeLength Name ----------------------- ---- d-----2020/7/1614:19koa_demoPS 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 0npm 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.748s1 package is looking for funding run `npm fund` for detailsPS C:\Users\Administrator\Desktop\ming\koa_demo>

启动项目
npm start

    推荐阅读