zl程序教程

您现在的位置是:首页 >  工具

当前栏目

koa2.x--路由

路由 -- Koa2
2023-09-27 14:26:51 时间

  • 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
  • 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
    在这里插入图片描述

学习资源推荐 学习资源推荐

安装

  • npm i koa-router

使用


const Koa=require('koa');
const router = require('koa-router')();
const app=new Koa();

router.get('/',async (ctx)=>{
    ctx.body="<h1>home</h1>";

})

router.get('/news',async (ctx)=>{
    ctx.body="<h1>news</h1>";

})

router.get('/newsinfo/:nid',async (ctx)=>{
    
    ctx.body="新闻详情"+ctx.params.nid;//获取动态路由的传值-ctx.params.nid

})


app.use(router.routes());  //启动路由
app.use(router.allowedMethods());//错误处理相关操作

app.listen(3000,()=>{
  console.log('run server---')
});