欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

node中间件KOA函数

发布时间:2025/3/15 编程问答 24 豆豆
生活随笔 收集整理的这篇文章主要介绍了 node中间件KOA函数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
const Koa = require('koa');
const app = new Koa()
//应用程序对象 中间件
// 发送HTTP KOA 接手HTTP
//中间件(其实就是 函数)
function test(){ console.log("seven month"); } //当请求发送过来的时候,将函数(中间件)注册到程序上 //前端发送一个http请求 来触发中间件 //koa 中 只会执行第一个中间件
app.use(async(ctx, next)=>{ //ctx 上下文 // next 下一个中间函数 console.log("7") const a = await next() //调用下一个中间件 // await 可以将promise 中对象 值 直接获取(不通过then) // await 对表达式求值 //await 阻塞线程(异步) (将异步变为同步) console.log(a) // a.then((res)=>{ // console.log(res) // }) console.log("8") }) // 洋葱模型(如果有await, 则需要在每个中间件函数前面加async next前面加上 await, ha)
app.use(async(ctx, next) =>{ console.log("9")
const res = await axios.get("http://7yue.pro") next()
// 对资源的操作 都是异步的 读文件 发送http请求 操作数据库
console.log('10') return "seven" })
// 打印结果为7 9 10 8
// 中间件(函数) return 会被强制转换成一个 Promise app.listen(3000);

转载于:https://www.cnblogs.com/fengch/p/11424949.html

总结

以上是生活随笔为你收集整理的node中间件KOA函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。