最近在研究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,就可以看到控制台里打印的信息了…