nodejs服务器端开发指koa2的使用

一、koaexpress的认识

  • 1、他们都是node-web开发的框架
  • 2、koa分两个版本,一个是1.*的使用Generator来写的,另外一个版本是使用async来写的
  • 3、koa的官网比较简单传送门

二、开始使用koa

  • 1、kao官网也介绍了,node的版本要大于7.6才可以使用async否则就要配置插件

  • 2、使用官方案例跑一个hello word

    const Koa = require("koa");
    const app = new Koa();
    app.use(async (ctx) => {
      ctx.body = 'Hello World';
    })
    
    app.listen(3000, () => {
      console.log(`服务器已经启动:localhost:3000`);
    });
    

三、koa官网如此的简单就是因为跟之前的express完全不一样,把我们常用的路由,静态文件等都单独出去了

四、使用路由

  • 1、安装包

    npm install koa-router --save
    
  • 2、使用

    **router文件**
    const Router = require('koa-router');
    const router = new Router();
    
    router.get('/', async (ctx) => {
      ctx.body = `<h1>你好</h1>`;
    })
    
    module.exports = router.routes();
    
    
  • 3、在主文件中使用

    app.use(require('./routers/user'));
    
  • 4、配置子路由

    const Router = require("koa-router");
    const router = new Router();
    
    router
      .get("/", async ctx => {
        ctx.body = `
          <ul>
            <li><a href="/hello">helloworld</a></li>
            <li><a href="/about">about</a></li>
          </ul>
        `;
      })
      .get("/hello", async ctx => {
        ctx.body = "helloworld";
      })
      .get("/about", async ctx => {
        ctx.body = "about";
      });
    
    module.exports = router.routes();
    

五、使用静态文件

  • 1、安装包

    npm install koa-static --save
    
  • 2、使用

    **主文件中**
    const static = require('koa-static');
    const path = require('path');
    // 静态存放地址
    const staticPath = './static';
    
    app.use(static(
      path.join(__dirname, staticPath)
    ))
    
    

六、get请求数据的获取

  • 1、get请求发送json到前端

    const Router = require("koa-router");
    const router = new Router();
    
    router.get("/query", async ctx => {
      // 获取url 
      const url = ctx.url;
      // 获取客户端的参数
      const query = ctx.query;
      // 获取?后面全部的参数
      const querystring = ctx.querystring;
      ctx.body = {
        url,
        query,
        querystring
      };
    });
    
    module.exports = router.routes();
    

七、post提交数据

  • 安装包

    npm install koa-bodyparser --save
    
  • 2、主文件配置koa-bodyparser中间件

    **主文件中**
    const bodyParser = require('koa-bodyparser');
    // 使用koa-bodyparser中间件
    app.use(bodyParser());
    
  • 3、配置路由

    router.post("/create", async ctx => {
      console.log(ctx.request.body);
      ctx.body = {
        name: ctx.request.body.name
      };
    });
    

八、koa配置跨域访问

  • 1、在主文件中配置中间件

    npm install --save koa2-cors
    var koa = require('koa');
    var cors = require('koa2-cors');
    
    var app = koa();
    app.use(cors({
      origin: function(ctx) {
        if (ctx.url === '/test') {
          return false;
        }
        return '*';
      },
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
      maxAge: 5,
      credentials: true,
      allowMethods: ['GET', 'POST', 'DELETE'],
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    }));
    

九、使用ejs模板引擎(现在流行前后端分开开发,不怎么用了)

  • 1、安装koa-views视图包

    npm install koa-views --save
    
  • 2、安装ejs模拟引擎

    npm install ejs --save
    
  • 3、主文件中配置使用的模板引擎

    const path = require('path')
    const views = require('koa-views');
    // 加载模板引擎
    app.use(views(path.join(__dirname, './view'), {
      extension: 'ejs'
    }))
    
    // 渲染模板
    app.use(async ctx => {
      let title = "Koa2";
      // 渲染模板及返回参数
      await ctx.render("index", {
        title
      });
    });
    

欢迎加入群聊,我们一起探讨前端技术栈

群号:560285778

这里写图片描述

十、查看博主更多文章

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值