koa2-router

koa2-router

koa2-router文档

// app.js
// 只看routes部分
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const index = require('./routes/index')
const users = require('./routes/users')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
// routes/index.js
const router = require('koa-router')()

router.get('/', async (ctx, next) => {
  global.console.log('index1')
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})
module.exports = router

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

// routes/users.js
const router = require('koa-router')()

router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

module.exports = router

在这里插入图片描述
在这里插入图片描述

koa2-cookie

koa2官网

cookies.get()

ctx.cookies.get(name, [options])

获得 cookie 中名为 name 的值,options 为可选参数:

cookies.set()

ctx.cookies.set(name, value, [options])

设置 cookie 中名为 name 的值,options 为可选参数:

  • maxAge 一个数字,表示 Date.now()到期的毫秒数
  • signed 是否要做签名
  • expires cookie有效期
  • pathcookie 的路径,默认为 /’
  • domain cookie 的域
  • secure false 表示 cookie 通过 HTTP 协议发送,true 表示 cookie 通过 - HTTPS 发送。
  • httpOnly true 表示 cookie 只能通过 HTTP 协议发送
  • overwrite 一个布尔值,表示是否覆盖以前设置的同名的Cookie(默认- 为false)。 如果为true,在设置此cookie时,将在同一请求中使用相同名称(不管路径或域)设置的所有Cookie将从Set-Cookie头部中过滤掉。

注意:Koa 使用了 Express 的 cookies 模块,options 参数只是简单地直接进行传递


谢谢你阅读到了最后
期待你,点赞、评论、交流

发布了65 篇原创文章 · 获赞 76 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_42752574/article/details/104855155