Express简单案例实战

前言

这次实战是模拟一个简单的增删改查的服务,数据是在一个json文件中存储

一、示例

1.1、服务代码

const express = require("express")
const fs = require("fs")
const { getDb, saveDb} = require("./db")

const app = express();

// 配置接字表单请求体方式
app.use(express.json())   //aapplication/json
app.use(express.urlencoded())   //application/x-www-form-urlencoded

// 获取整个列表
app.get('/todos', async (req,res) => {
    try {
        const db = await getDb()
        res.status(200).json(db.todos)
    } catch (error) {
        res.status(500).json({
            error: error.message
        })
    }
   
})

// 获取单个
app.get('/todos/:id',async (req,res) => {
    try {
        const db = await getDb()
        const todo = db.todos.find(todo => todo.id === Number.parseInt(req.params.id)) 
        if(!todo){
            return res.status(404).end("没有该数据")
        }
        res.status(200).json(todo)
    } catch (error) {
        res.status(500).json({
            error: error.message
        })
    }
})

// 添加数据
app.post('/todos', async (req,res) => {
    try {
        // 获取客户端请求参数
        const todo = req.body

        console.log(todo)
        // 数据验证
        if(!todo.title){
            return  res.status(422).json({
                error: "The field title is required"
            })
        }
        // 存储数据
        const db = await getDb()
        console.log(db.todos)

        const lastTodo = db.todos[db.todos.length - 1]
        todo.id = lastTodo? lastTodo.id + 1 : 1
        db.todos.push(todo)
        await saveDb(db) 
        res.status(200).json(todo)
    } catch (error) {
       res.status(500).json({
           error: error.message
       })
    }
})

// 修改
app.patch('/todos/:id', async (req,res) => {
   try {
    //    获取表单数据
    const todo = req.body
    // 查找修改项
    const db = await getDb()
    const ret = db.todos.find(todo => todo.id === Number.parseInt(req.params.id))

    if(!ret){
        return res.status(404).end()
    }
    // 将请求的数据覆盖原本的数据
    Object.assign(ret,todo)

    await saveDb(db)

    res.status(201).json(ret)
   } catch (error) {
       res.status(500).json({
           error: error.message
       })
   }
})

// 删除
app.delete('/todos/:id', async(req,res) => {
    try {
        const todoId = Number.parseInt(req.params.id)
        const db = await getDb()
        const index = db.todos.findIndex(todo => todo.id === todoId)
        if(index === -1)
        return res.status(404).end("删除失败,没有该记录")

        db.todos.splice(index,1)
        await saveDb(db)
        return res.status(204).end("删除成功!")
    } catch (error) {
        res.status(500).json({
            error: error.message
        })
    }
})

app.listen(3000 , () => {
    console.log('Server running at http://localhost:3000')
})

1.2、操作数据的代码

const fs = require('fs')
// 使用utils将函数promise化
const {promisify}  = require('util')
const path = require('path')

const dbPath = path.join(__dirname,'./db.json')

const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)


// 取数据
exports.getDb = async () => {
    const data = await readFile(dbPath,'utf-8')
    return JSON.parse(data)
}

// 存数据
exports.saveDb = async (db) => {
    const data = JSON.stringify(db, null, '  ')
    await writeFile(dbPath,data)
}

1.3、原始json数据

{
  "todos": [
    {
      "id": 1,
      "title": "吃饭"
    },
    {
        "id": 2,
        "title": "睡觉"
    },
    {
    "id": 3,
    "title": "打豆豆"
    }
  ]
}

二、测试

2.1、查出所有数据

在这里插入图片描述

2.2、查出指定数据

在这里插入图片描述

2.3、增加一条数据

在这里插入图片描述

2.4、修改一条数据

在这里插入图片描述

2.5、删除一条数据

在这里插入图片描述
204表示删除成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韭菜盖饭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值