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