0
点赞
收藏
分享

微信扫一扫

前端歌谣-第柒拾捌课-Koa获取请求参数讲解


前言

大家好 我是歌谣 今天给大家带来node中关于koa静态资源模块的讲解

初始化项目

npm init -y

安装koa和路由和解析静态资源和获取请求参数

npm i koa
npm i koa-router
npm i koa-static
npm i koa-bodyparser

案例

login.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我是登录</title>
</head>

<body>
    <div>用户名:<input id="username" />
    </div>
    <div>密码:<input type="password" id="password" />
    </div>
    <div>
        <button id="login">登录</button>
    </div>
    <div>
        <button id="loginpost">登录-post</button>
    </div>
</body>
<script>
    var oLogin=document.querySelector("#login")
    var oLoginPost=document.querySelector("#loginpost")
    var oUsername=document.querySelector("#username")
    var oPassword=document.querySelector("#password")
    oLogin.onclick=()=>{
        console.log(oUsername.value,oPassword.value)
        fetch(`/api/user?username=${oUsername.value}&password=${oPassword.value}`)
        .then(res=>res.text()).then(res=>{
            console.log(res)
        })
    }
    oLoginPost.onclick=()=>{
        console.log(oUsername.value,oPassword.value)
        fetch(`/api/user`,{
            method:"POST",
            body:JSON.stringify({
                username:oUsername.value,
                password:oPassword.value
            }),
            headers:{
                "Content-Type":"application/json"
            }
        }).then(res=>res.text()).then(res=>{
            console.log(res)
        })
    }
</script>
</html>

user.js

const Router = require("koa-router")
const router = new Router()
router.post("/",(ctx,next)=>{
    console.log(ctx.request.body)
    ctx.body={
        ok:"1",
        info:"添加成功"
    }
})
router.put("/:id",(ctx,next)=>{
    ctx.body={
        ok:"1",
        info:"修改成功"
    }
})
router.del("/:id",(ctx,next)=>{
    ctx.body={
        ok:"1",
        info:"删除成功"
    }
})
router.get("/",(ctx,next)=>{
    console.log(ctx.query,ctx.querystring)
    ctx.body=["11111","22222"]
})

module.exports=router

get请求

前端歌谣-第柒拾捌课-Koa获取请求参数讲解_arcgis

post请求

前端歌谣-第柒拾捌课-Koa获取请求参数讲解_arcgis_02


举报

相关推荐

0 条评论