Hello koa & koa-router

Hello koa & koa-router_第1张图片
项目目录
Hello koa & koa-router_第2张图片
package.json

app.js:

const Koa = require('koa')

const app = new Koa()

app.use(async (ctx, next) => {
  console.log(`${ctx.request.method} ${ctx.request.url}`)
  await next()
})

app.use(async (ctx, next) => {
  const start = new Date().getTime()
  await next()
  const ms = new Date().getTime() - start
  console.log(`Time: ${ms}ms`)
})

app.use(async (ctx, next) => {
  await next()
  ctx.response.type = 'text/html'
  ctx.response.body = '

hello koa2

' }) app.listen(3001) console.log("runing in port 3001...")
Hello koa & koa-router_第3张图片
node app.js

app-router.js:

const Koa = require('koa')

const router = require('koa-router')()

const bodyParser = require('koa-bodyparser');

const app = new Koa()

// 解析原始request请求,然后,把解析后的参数,绑定到ctx.request.body
app.use(bodyParser());

// log request url
app.use(async (ctx, next) => {
  console.log(`${ctx.request.method} ${ctx.request.url}`)
  await next()
})

// add url-route
router.get('/hello/:name', async (ctx, next) => {
  let name = ctx.params.name
  // console.log("Hello-ctx: ", ctx)
  ctx.response.body = `

Hello, ${name}

` }) router.get('/', async (ctx, next) => { // console.log("Index-ctx: ", ctx) ctx.response.body = `

Index

Name:

Passorrd:

` }) router.post('/signin', async (ctx, next) => { let { name, password } = ctx.request.body if (name === 'koa' && password === '123456') { ctx.response.body = `

Welcome, ${name}

` } else { ctx.response.body = 'Loging failed' } }) // add router middleware app.use(router.routes()) app.listen(3001) console.log('runing in port 3001....')
Hello koa & koa-router_第4张图片
node app-router.js

nodemon

以 nodemon 实现热更新。


Hello koa & koa-router_第5张图片
项目目录

package.json:

{
  "scripts": {
    "start": "node bin/www",
    "dev": "./node_modules/.bin/nodemon bin/www"
  },
  "dependencies": {
    "koa": "2.0.0",
    "koa-body": "^4.2.0",
    "koa-router": "^10.0.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.4"
  }
}

bin/www:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('demo:server');

const port = 3002

// app.listen(3002);
// console.log('server is ready in port @' + port)

const server = app.listen(port, () => {

  let addr = server.address()

  let bind = typeof addr === 'string' ? 'pipe' + addr : 'port' + addr.port

  console.log('server is ready in port @' + port)

  debug('Listening on ' + bind)
})

app.js:

const Koa = require('koa');

// 创建一个Koa对象表示web app本身:
const app = new Koa();


// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
  await next();
  ctx.response.type = 'text/html';
  ctx.response.body = '

Hello, koa2!

'; }); module.exports = app

启动:

yarn dev

你可能感兴趣的:(Hello koa & koa-router)