zoukankan      html  css  js  c++  java
  • koa2简单demo

    // 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
    const Koa = require('koa');
    const Router = require('koa-router');
    // 创建一个Koa对象表示web app本身:
    const app = new Koa();
    const router=new Router();
    
    
    // 打印request URL:
    app.use(async (ctx, next) => {
        console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
        await next();
    });
    
    
    // 对于任何请求,app将调用该异步函数处理请求:
    router.get('/', async ( ctx ) => {
      ctx.response.type = 'text/html';
      ctx.body = 'hi'
    })
    router.get('/getList', async ( ctx ) => {
      ctx.response.type = 'text/html';
      ctx.body = 'haha'
    })
    
    
    // 加载路由中间件
    //解释:app.use 加载用于处理http請求的middleware(中间件),当一个请求来的时候,会依次被这些 middlewares处理。
    app.use(router.routes());
    
    // 在端口3000监听:
    app.listen(3000, () => {
      console.log('[myapp]已经运行,端口为300')
    })


    如果不用koa-router中间件的话,原始的写法可能比较麻烦而且显得愚蠢,建议学习还好,以后就别用了

     const main=ctx=>{
         let path=ctx.request.path;
         if(path=='/'){
             ctx.response.type = 'text/html';
             ctx.response.body='<h1>首页</h1>'
         }else if(path=='/list') {
             ctx.response.type = 'text/html';
             ctx.response.body='<h1>列表</h1>'
         }else{
             ctx.response.type = 'text/html';
             ctx.response.body='<h1 style="color: red">无匹配</h1>'
         }
    
     }

    参考:http://cnodejs.org/topic/58ac640e7872ea0864fedf90

  • 相关阅读:
    linux 基础笔记(一)
    wysiwyg加ckeditor加 代码高亮
    将html转换为Drupal模板文件的一般步骤
    最重要的7个Drupal内核模板文件
    drupal模板命名规则
    mysql存储过程和事件
    阿里云图片压缩上传代码
    BeanUtils No value specified for Date的解决方法
    mysql SQLyog导入导出csv文件
    mysql去除重复查询的SQL语句基本思路
  • 原文地址:https://www.cnblogs.com/dshvv/p/7692051.html
Copyright © 2011-2022 走看看