服务器端代码
有index.js和package.json
- 文件名index.js
const express = require("express") const jwt = require("jsonwebtoken") const app = express() let STU_ARR = [ { id: "1", name: "孙悟空", age: 18, gender: "男", address: "花果山" }, { id: "2", name: "猪八戒", age: 28, gender: "男", address: "高老庄" }, { id: "3", name: "沙和尚", age: 38, gender: "男", address: "流沙河" }, ] /********************中间件***********************************/ app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500"); res.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,PATCH"); res.setHeader("Access-Control-Allow-Headers", "Content-type,Authorization"); next(); }) /********************路由***********************************/ // 登录路由 app.post("/login", (req, res) => { const { username, password } = req.body; if (username == "admin" && password == "123") { // 生成token const token = jwt.sign({ id: "12345", username: "admin", nickname: "超级管理员" }, "chaojianquanmima", { expiresIn: "1d" }) res.send({ status: "ok", data: { token, nickname: "超级管理员" } }) } else { res.status(403) res.send({ status: "error", data: "用户名或密码错误" }) } }) // 获取学生信息的路由 app.get("/students", (req, res) => { console.log("收到students的get请求"); try { // 获取、解码token const token = req.get("Authorization").split(" ")[1]; const decodeToken = jwt.verify(token, "chaojianquanmima") res.send({ status: "ok", data: STU_ARR }); } catch (e) { console.log("解码错误,token无效"); res.status(403).send({ status: "error", data: "数据无效" }) } }) // 查询某个学生的信息 app.get("/students/:id", (req, res) => { const id = req.params.id; const stu = STU_ARR.find((item) => { return item.id === id }); if (stu) { res.send({ status: "ok", data: stu }) } else { res.status(403); res.send({ status: "failed" }) } }) // 添加学生信息的路由 app.post("/students", (req, res) => { console.log("收到students的post请求", req.body); const { name, age, gender, address } = req.body; const stu = { id: +STU_ARR.at(-1).id + 1 + "", name: name, age: +age, gender: gender, address: address }; // 获取学生信息 STU_ARR.push(stu); res.send({ status: "ok", data: stu }); }) // 删除学生的路由 app.delete("/students/:id", (req, res) => { console.log("向/students发送delete请求"); const id = req.params.id; for (let i = 0; i < STU_ARR.length; i++) { if (STU_ARR[i].id === id) { const delStu = STU_ARR[i] STU_ARR.splice(i, 1); res.send({ status: "ok", data: delStu }); return } } res.status(403); res.send({ status: "error", data: "学生id不存在" }); }) // 修改学生信息 app.put("/students", (req, res) => { console.log("向/students发送put请求"); const { id, name, age, gender, address } = req.body; const editStu = STU_ARR.find((item) => { return item.id === id }) if (editStu) { editStu.name = name; editStu.age = age; editStu.gender = gender; editStu.address = address; res.send({ status: "ok", data: editStu }) } else { res.status(403) res.send({ status: "error", data: "学生不存在" }) } }) // app.get("/test", (req, res) => { console.log("收到发送给/test的get请求"); }) app.listen(3000, () => { console.log("服务器启动"); })
-
package.json
{ "name": "my-server", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "express": "^4.18.2", "jsonwebtoken": "^9.0.1" } }
客户端代码
- login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> table { border-collapse: collapse; width: 50%; } tr, td { font-size: 20px; text-align: center; border: 1px solid black; } caption { font-size: 30px; font-weight: bold; } </style> </head> <body> <div id="login"> <h1>请登录后再操作</h1> <h2 id="info"></h2> <form> <div> <input type="text" id="username"> </div> <div> <input type="password" id="password"> </div> <div> <input type="button" id="login-btn" value="登录"> </div> </form> </div> <div id="list"></div> <script> const login = document.querySelector("#login"); const info = document.querySelector("#info"); const login_btn = document.querySelector("#login-btn"); const username = document.querySelector("#username"); const password = document.querySelector("#password"); if (localStorage.getItem("token")) { login.innerHTML = ` <h1>欢迎超级管理员回来</h1> <hr> <button id="load-btn">加载数据</button> <button id="out-btn">注销</button> `; } else { login_btn.addEventListener("click", () => { fetch("http://localhost:3000/login", { method: "post", headers: { "Content-type": "application/json" }, body: JSON.stringify({ username: username.value.trim(), password: password.value.trim() }) }) .then(res => res.json()) .then(res => { console.log(res); if (res.status == "ok") { info.innerText = "登录成功"; login.innerHTML = ` <h1>欢迎${res.data.nickname}回来</h1> <hr> <button id="load-btn">加载数据</button> <button id="out-btn">注销</button> `; localStorage.setItem("token", res.data.token) localStorage.setItem("nickname", res.data.nickname) } else { info.innerText = "用户名或密码错误"; } }) .catch(err => { console.log("代码运行出错了"); }) }) } const loadBtn = document.querySelector("#load-btn"); loadBtn.onclick = function () { // 读取学生信息 fetch("http://localhost:3000/students", { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }) .then(res => { return res.json() }) .then(res => { if (res.status === "ok") { console.log(res); const table = document.createElement("table"); list.appendChild(table); table.insertAdjacentHTML("beforeend", "<caption>学生列表</caption>"); for (let item of res.data) { const tr = document.createElement("tr"); for (let probname in item) { const td = document.createElement("td"); td.innerText = `${item[probname]}`; tr.appendChild(td); } table.appendChild(tr); } } }) .catch(err => { console.log("出错了"); }) } // fetch("http://localhost:3000/students", { // method: "post", // headers: { // "Content-type": "application/json" // }, // body: JSON.stringify({ // name: "min", // age: "18", // gender: "女", // address: "bupt" // }) // }) // .then(res => res.json()) // .then(res => console.log(res)) // .catch(err => console.log(err)) </script> </body> </html>
- index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="btn">点我加载数据</button> <button id="btn2">点我加载数据2</button> <div id="root"> </div> </body> <script> const btn = document.querySelector("#btn"); const btn2 = document.querySelector("#btn2"); const root = document.querySelector("#root"); btn.addEventListener("click", () => { fetch("http://localhost:3000/students") .then(res => { if (res.status === 200) { // 获取数据 return res.json() } else { throw new Error("加载失败!") } }) .then(res => { if (res.status === "ok") { const table = document.createElement("table"); root.appendChild(table); for (let item of res.data) { const tr = document.createElement("tr"); for (let probname in item) { const td = document.createElement("td"); td.innerText = `${item[probname]}`; tr.appendChild(td); } table.appendChild(tr); } } }) .catch(err => { console.log("出错了"); }) }) btn2.onclick = function(){ fetch("http://localhost:3000/students/1", { method:"delete", headers:{ "Content-type":"application/json" }, body:JSON.stringify({ }) }) } </script> </html>
标签:status,const,res,req,rest,id,发送,data,fetch From: https://www.cnblogs.com/minmin1009/p/17617971.html