美文网首页
Hello koa & koa-router

Hello koa & koa-router

作者: liwuwuzhi | 来源:发表于2021-04-29 16:38 被阅读0次
    项目目录 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 = '<h1> hello koa2 </h1>'
    })
    
    app.listen(3001)
    console.log("runing in port 3001...")
    
    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 = `<h1>Hello, ${name}</h1>`
    })
    
    router.get('/', async (ctx, next) => {
      // console.log("Index-ctx: ", ctx)
      ctx.response.body = `
      <h1>Index</h1>
      <form action='/signin' method='post'>
        <p>Name: <input name='name' value='koa' /></p>
        <p>Passorrd: <input name='password' type='password' value='123456' /></p>
        <p><input type='submit' value='submit' /></p>
      </form>
      `
    })
    
    router.post('/signin', async (ctx, next) => {
      let { name, password } = ctx.request.body
      if (name === 'koa' && password === '123456') {
        ctx.response.body = `<h1>Welcome, ${name}</h1>`
      } else {
        ctx.response.body = 'Loging failed'
      }
    })
    
    // add router middleware
    app.use(router.routes())
    
    app.listen(3001)
    console.log('runing in port 3001....')
    
    node app-router.js

    nodemon

    以 nodemon 实现热更新。


    项目目录

    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 = '<h1>Hello, koa2!</h1>';
    });
    
    module.exports = app
    

    启动:

    yarn dev
    

    相关文章

      网友评论

          本文标题:Hello koa & koa-router

          本文链接:https://www.haomeiwen.com/subject/pcewrltx.html