【node学习】koa2实现简单的表单提交 入门前端+后台完整代码

开始一个小系列的博客,记录自己的学习过程。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" οnsubmit="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>




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值