Node框架koa的简单使用

1. Koa

  • 安装koa: npm i koa -s,下同

    const Koa  = require("koa")  // 安装好之后,引入模块,下同
    const app = new Koa()
    
  • 使用koa

    app.use(static(__dirname, './img/img.png'))
    app.use(router.routes())
    app.listen(1234)
    

2.Koa-router:路由

  • 安装koa-router:

    const Router = require("koa-router")
    const router = new Router()
    
  • 使用:

    router.get("/index", (ctx,next) => {
        ctx.body = $index.html()  //使用了cheerio模块
        console.log(data)
    })
    

3.Koa-static:加载静态文件

可通过localhost:1234/img.png访问

  • 安装koa-static

    const static = require('koa-static')
    
  • 使用:

    app.use(static(__dirname, './img/img.png'))
    

4.Koa-view:渲染模板

  • 安装koa-view

    const view = require('koa-views')
    
  • 使用:

    app.use(view(__dirname+'/view'),{
    	map:{
            html: '模板引擎名称'
        }
    })
    router.get('/index', async ctx =>{
        await ctx.render("index", {
            newsData:newData, // 传入模板中的变量
            totalPage,
            p
        })
    })
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值