版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33168578/article/details/80757013
开始一个小系列的博客,记录自己的学习过程。koa2实现简单的登录页面的表单提交。入门级别,没有数据库操作,开始接触koa2小接口的编写。
推荐一个不错的koa2的基础教程:https://blog.csdn.net/lszy16/article/list/2
前端请求到数据的效果图:
后端代码实现:
const Koa=require('koa')
const router=require('koa-router')() //路由插件
const fs=require('fs') //文件系统 读取/写入文件
const app =new Koa()
const bodyParser=require('koa-bodyparser') //获取post数据
app.use(bodyParser())
router.get('/user',async(ctx,next)=>{
ctx.type='html'
ctx.body=fs.createReadStream('./static/2.html') //读取静态文件。。此处为前端文件
})
router.post('/user/regiser',async(ctx,next)=>{ //表单提交接口
console.log(ctx.request.body)
let {name,password}=ctx.request.body
ctx.response.set("Content-Type", "application/json")
if(name==='aaa'&&password==='123456'){
ctx.status = 200;
ctx.body = { //post返回接口数据
status_code:'0',
data: 'register success'
};
}else{
ctx.body = {
status_code:'1001',
data: '账号或密码错误'
};
}
})
app.use(router.routes())
app.listen(3000,()=>{
console.log('server')
})
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="form" action="##" method="post" onsubmit="return false" enctype:'multipart/form-data'>
<input type="text" name="name">
<input type="password" name="password">
<button class="btn">go</button>
</form>
</body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$(".btn").click(function(){
console.log(4444)
$.ajax({
url:'/user/regiser',
type:"post",
data:$("#form").serialize(),
success:function(res){
console.log(res)
}
})
})
</script>