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

本文介绍了如何在Node.js项目中通过Koa框架处理静态资源和实现RESTfulAPI,包括GET、POST请求的路由配置与参数解析。作者通过登录页面和user.js文件展示了基本的HTTP请求操作。
摘要由CSDN通过智能技术生成

前言

大家好 我是歌谣 今天给大家带来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请求

在这里插入图片描述

post请求

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值