Node慕课网学习笔记(三)

1. koa2 的安装与使用

  1. 新建文件夹
  2. npm init
  3. npm i koa --save

代码演示

新建 index.js 文件

const Koa = require('koa')  // commonjs 模块化规范
const app = new Koa()

// ctx context 上下文
app.use(async (ctx) => {
  ctx.body = 'hello world'
})

app.listen(3000)    // web server 监听的 3000 端口 

2. koa2 的环境搭建

使用脚手架 koa-generator 创建 koa2 项目

介绍项目

在项目中新建一个路由

  1. 使用脚手架 koa-generator 创建 koa2 项目

    • npm install -g koa-generator (全局安装脚手架
    • koa2 test4 (将 koa2 安装在 test4 文件夹下)
    • 在 test4 文件夹下 npm install
    • 启动 npm run dev
    • 浏览器 localhost:3000 查看
  2. 项目介绍

    app.js 中

    • onerror(app) //错误处理器

    • bodyparser() 用于 request body 转换

    • app.use(require(‘koa-static’)(__dirname + ‘/public’)) //***静态文件服务***的功能

      • 表示在 public 文件夹下的文件,都可以通过:
      • localhost:3000/images/1.jpg 这种方式来访问这个源文件
    • app.use(views(__dirname + ‘/views’, { // 服务端模板引擎

      extension: ‘pug’

      }))

  3. 新建路由

    1. 定义路由文件

      • routes 文件夹下新建 comments.js

      • comments.js 代码:

        const router = require('koa-router')()
        
        router.prefix('/api')   // 前缀
        
        // 定义路由:模拟获取留言板列表
        router.get('/list', async (ctx) => {
          ctx.body = 'api list'
        })
        
        // 定义路由:模拟创建留言内容
        router.post('/create', async (ctx) => {
          ctx.body = 'api create'
        })
        
        module.exports = router // 输出
        
  4. 在 app.js 文件中引入路由

    const comments = require('./routes/comments')

  5. 注册路由

    `app.use(comments.routes(), comments.allowedMethods())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值