node.js、koa2开发微信小程序后端(一)

本文介绍Node.js的基础及如何使用Koa2框架搭建服务器。通过实例演示了Node.js环境搭建、Koa2安装配置过程,并详细解析了中间件的工作原理及洋葱模型的执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

node.js能力

  1. 脱离浏览器运行js
  2. NodeJS Stream(前端工程化基础)
  3. 服务端API
  4. 作为中间层

第一段nodejs代码

安装node.js环境;打开vs code 新建文件夹island ;在该文件夹下新建test.js文件

function test(){
    console.log("helloworld")
}
test()

打开终端,输入node test.js运行代码

后端:主要读写数据库 提供API

安装koa2

在终端中输入npm -v测试当前npm版本

npm init初始化项目配置文件 一直回车选择默认配置

npm i koa安装koa2

安装完成时候终端会显示+koa@2.x.x

导入导出方式

  1. commonJS const var_name = require("xxx")
  2. ES6 import from(nodejs中暂时不支持)
  3. AMD

在文件夹下新建app.js

//app.js
const Koa = require('koa')

const app = new Koa() 

//应用程序对象 中间件

//函数
function test(){
    console.log("helloworld")
}

//注册
app.use(test)//接收到http请求之后调用use

app.listen(3000)//端口号

从前端发送请求到服务端:打开浏览器,输入localhost:3000

这时,终端打印出了helloworld

中间件一般来说我们使用箭头函数

app.use(()=>{ 
    //匿名函数
    console.log("helloworld")
})
app.use(()=>{
    //匿名函数
    console.log("helloworld1")
})

这样的话默认执行第一个中间件。其实koa给app.use提供了两个默认参数。

app.use((ctx,next)=>{//ctx为上下文, 
    //匿名函数
    console.log("helloworld")
    next()
})
app.use(()=>{
    //匿名函数
    console.log("helloworld1")
})

洋葱模型

app.use(async (ctx,next)=>{//ctx为上下文, 
    //匿名函数
    console.log("1")
    await next()
    console.log("2")
})
app.use(async (ctx,next)=>{
    //匿名函数
    console.log("3")
    await next()
    console.log("4")
})
//如果不加async和await,不能保证所有的中间件都是按洋葱模型执行的

我们可以看到打印到终端的顺序为 1 3 4 2

app.use((ctx,next)=>{//ctx为上下文, 
    //匿名函数
    console.log("1")
    const a = next()
    console.log(a)
    console.log("2")
})

由结果可知,next()返回的结果是一个Promise。

async和await必须搭配使用。

await相当于一个求值关键字,await加任意一个表达式,都可以对这个表达式求值。

app.use(async(ctx,next)=>{//ctx为上下文, 
    //匿名函数
    console.log("1")
    const a =await next()
    /* a.then((res)=>{
        console.log(res)
    }) */
    console.log(a)
    console.log("2")
})
app.use((ctx,next)=>{
    //匿名函数
    console.log("3")
    //next()
    console.log("4")
    return "abc"
})

阻塞线程

app.use(async (ctx,next)=>{
    const anxios = require('axios')
    const start = Date.now()
    const res = await anxios.get("http://7yue.pro")
    const end = Date.now()
    console.log(end-start)
    //next() 对资源 读文件 发送http请求 操作数据库等都是异步的
    
})

不加async和anxious时,end-start的值为0,而加上之后,值为896。阻塞当前线程,等待这次异步调用结果的返回。中间件传参时将接受参数的变量放在next后,就能保证后面的中间件全部执行完成(如果不按照洋葱模型,则无法保证)。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值