手把手擼一個Koa前後端分離的例子

最近在研究Koa2的知識,跟着視頻學了很久,視頻中都是類似於寫jsp和thinkphp一樣的例子,前端頁面全部都是用ejs等等渲染出來的,都9012年了,前後端都分離這麼久了,怎麼可能還前後端代碼耦合在一起,嚇得我虎軀一震,趕緊查了一下資料,結合自己多年的聰明才智,擼了一個前後端分離的例子,簡單明瞭,直接上代碼:
後端代碼:

  /*jshint esversion:8*/
  var Koa=require('koa'),
      router = require('koa-router')(),
      views = require('koa-views'),
      cors = require('koa2-cors');
      bodyParser = require('koa-bodyparser');

  var app=new Koa();

  app.use(bodyParser());

  app.use(cors({
    origin: function(ctx) {
      ctx.set("Access-Control-Allow-Origin", "*");
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  }));

  //接收post提交的數據
  router.post('/doAdd',async (ctx)=>{
      console.log(ctx.request.body);
      // ctx.body=ctx.request.body;  //獲取表單提交的數據
      ctx.body = {
        data: ctx.request.body
      }
  })

  app.use(router.routes());   /*啓動路由*/
  app.use(router.allowedMethods());
  app.listen(3000);

很簡單吧,起了個服務,寫了一個post接口doAdd,接下來我們就是調用了,可以用你喜歡的各種方式去調用,這裏我還是以風靡了幾十年的ajax爲例:

  <html>

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>測試專用</title>
  </head>

  <body>
    用戶名: <input type="text" id="username" name="username" />
    <br />
    密 碼: <input type="password" id="password" name="password" />
    <br />
    <br />
    <button type="submit" id="submit">提交</button>

    <script src="../js/jquery-2.1.1.min.js"></script>

    <script>
      $('#submit').click(function(){
        $.ajax({
          type: "POST",
          url: "http://127.0.0.1:3000/doAdd",
          contentType: 'application/x-www-form-urlencoded;charset=utf-8',
          data: {
            username:$("#username").val(),
            password:$("#password").val()
          },
          dataType: "json",
          success: function(data){
              console.log(data);
          },
          error:function(e){
              console.log(e);
          }
      });
      })
    </script>
  </body>
  </html>

接下來開個server,就可以看到控制檯裏打印的信息了…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章