【金秋打卡】第5天 《Node.js+Koa2+MySQL 打造前后端分離精品項目》
课程名称:Node.js+Koa2+MySQL打造前后端分离精品项目《旧岛》
课程章节:第2章 【深入理解KOA】Koa2的那点事儿与异步编程模型
视频:2-5 KOA的中间件
2-6 洋葱模型
2-7 强制Promise
课程讲师: 七月
课程内容:
端口号确信没有被其他的应用程序使用
定义一个中间件就是定义一个普通的函数
const Koa = require('koa') //导入Koa
const app = new Koa() //实例化
//应用程序对象 中间件
//发送HTTP KOA接收HTTP
//函数
function test() {
console.log('hello world');
}
//注册
//app.use(test)
//或者
// app.use(() => {
// console.log('hello world 1');
// })
//或者
app.use((ctx, next) => {
console.log('hello world 1');
next()
})
app.use((ctx, next) => {
console.log('hello world 2');
})
app.listen(3000) //启动Koaapp.use((ctx, next) => {
console.log('hello world 1');
next()
console.log('hello world 2');
})
app.use((xtx, next) => {
console.log('hello world 3');
next()
console.log('hello world 4');
})
//显示顺序 1、3、4、2app.use(async (ctx, next) => {
console.log('hello world 1');
await next()
console.log('hello world 2');
})
app.use(async (xtx, next) => {
console.log('hello world 3');
await next()
console.log('hello world 4');
})
//如果不加async和await 很难保证所有的中间件都是按照洋葱模型的模式执行app.use((ctx, next) => {
console.log('hello world 1');
const a = next()
console.log(a);
console.log('hello world 2');
})
app.use((xtx, next) => {
console.log('hello world 3');
//next()
console.log('hello world 4');
})
//输出为
hello world 1
hello world 3
hello world 4
Promise { undefined }
hello world 2app.use((ctx, next) => {
console.log('hello world 1');
const a = next()
console.log(a);
console.log('hello world 2');
})
app.use((xtx, next) => {
console.log('hello world 3');
//next()
console.log('hello world 4');
return 'abc'
})
//输出为
hello world 1
hello world 3
hello world 4
Promise { 'abc' }
hello world 2课程收获:
这节课终于开始上代码了。七月老师用的开发环境是VS Code。 从最基本的Koa导入开始,导入之后要实例化,实例化之后要启动,KOA实际上是接收HTTP请求, 编写好代码之后,在终端运行node test.js 然后浏览器访问localhost之后(注意写好端口号)在VS Code的终端可以看到输出。之后讲到了洋葱模型。
七月老师非常注重在讲编程知识的同时,讲编程思维,讲知识和知识之间的关系。编程是实践性非常强的工作,学习知识最好的方法是放到项目中。做项目的目的不是做项目,最终要做出来自己的项目,业务承载的是编程知识。明天继续刷后边的课程。
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦


