node js05/ 搭建api服务器 添加,获取,删除

 原代码步骤

1.下载第三方包 then-fs

npm i then-fs

2.引入JSON文件

原代码

// 需求: es6模块化,用async、await和then-fs模块实现操作文件数据
//     功能:  增删改查;
// 导入对应模块
import thenFs from 'then-fs';
// ES6中不支持 __dirname ,所以当前这个案例还是使用相对路径;
const url = './06.json';

// 1.查询; - await必须出现在async修饰的函数中;
export async function getData() {
    try {
        // 利用 thenFs 读取文件内容
        const str = await thenFs.readFile(url, 'utf-8'); // 返回的是Promise
        // 把str转换为数组
        const arr = JSON.parse(str);
        // 返回数组, 将来别人调用这个函数,就可以获取数组了
        return arr;
    } catch (e) {
        return '获取图书列表失败';
    }
}
// // 测试获取
// getData().then(res => console.log(res));

// 2.添加; - await必须出现在async修饰的函数中;
export async function addData(obj) {
    // 先读取文件中的数据
    const arr = await getData();
    // 然后向数组中添加元素
    obj.id = arr[arr.length - 1].id * 1 + 1;
    arr.push(obj);
    // 写入数据
    try {
        // 代码 thenFs.writeFile()之前最好写await,有阻塞功能;
        await thenFs.writeFile(url, JSON.stringify(arr));
        return '添加成功';
    } catch (e) {
        return '添加失败';
    }
}
// // 测试添加
// addData({
//     bookname: '三体', author: '刘慈欣', publisher: '武汉人民出版社'
// }).then(res => console.log(res));

// 3.删除; - await必须出现在async修饰的函数中;
export async function delData(id) {
    // 先读取文件中的数据
    const arr = await getData();
    // 过滤模拟删除功能
    const newArr = arr.filter(item => item.id != id);
    // 写入文件
    try {
        // 代码 thenFs.writeFile()之前最好写await,有阻塞功能;
        await thenFs.writeFile(url, JSON.stringify(newArr));
        return '删除成功';
    } catch (e) {
        return '删除失败';
    }
}
// // 测试删除
// delData(5).then(res => console.log(res));

// 4.修改;
export async function putData(obj) {
    // 先读取文件中的数据
    const arr = await getData();
    // 修改 - 先删除,在添加
    const index = arr.findIndex(item => item.id == obj.id);
    arr.splice(index, 1, obj);
    // 写入数据
    try {
        // 代码 thenFs.writeFile()之前最好写await,有阻塞功能;
        await thenFs.writeFile(url, JSON.stringify(arr));
        return '修改成功';
    } catch (e) {
        return '修改失败';
    }
}
// // 测试
// putData({
//     id: 1, bookname: '三国演义-后传',author: '罗贯东',publisher: '传智人民出版社'
// }).then(res => console.log(res))

// 默认导出
export default { getData, addData, delData, putData }

步骤说明

1.下载第三方包 

npm i express 

2.将上面原代码导入进来

import book from './obtain.js';

3.下载第三方包 全局跨域

npm i cors

nodejs/api 查看信息

import express from 'express';
import btain from './obtain.js';

const app = express()

app.get('/aaa/bbb', async (req, res) => {
    const arr = await btain.getData()
    // 支持浏览器ajax跨域访问, * 代表任意人都可以来请求
    res.setHeader('Access-Control-Allow-Origin', '*')
    if (arr instanceof Array) {
        res.send({ code: 200, msg: '获取图书列表成功', data: arr })
    } else {
        res.send({ code: 501, msg: '获取图书列表失败' })
    }
    // res.send('获取图书列表成功')

})
// 启动 web 服务器 
app.listen(8080, () => {
    console.log(' http://127.0.0.1:8080')
})

nodejs/api 添加信息

import express from 'express';

import book from './obtain.js';
const app = express()

app.use(express.urlencoded({ extended: true }))
app.use(express.json())

//设置全局跨域
const cors = require('cors')
app.use(cors())
//post
app.post('/ccc/ddd', async (req, res) => {

    const arr = await book.addData(req.body)
    // console.log(arr);
    if (arr == '添加成功') {
        res.send({ code: 201, msg: '添加图书成功' })
    } else {
        res.send({ code: 501, msg: '添加图书失败' })
    }
    // res.send(`添加图书成功`)
})



//启动服务器
app.listen(5521, () => {
    console.log(`http://127.0.0.1:5521`);
})


 

nodejs/api 删除信息

import express from 'express';

import book from './obtain.js';



const app = express()

app.use(express.urlencoded({ extended: true }))
app.use(express.json())

//设置全局跨域
const cors = require('cors')
app.use(cors())

//post DELETE
app.delete('/eee/fff', async (req, res) => {
    res.set('Access-Control-Allow-Origin', "*"); // 设置响应头
    const arr = await book.delData(req.query.id)
    console.log(arr);
    if (arr == '删除成功') {
        res.send({ code: 201, msg: '删除图书成功' })

    } else {
        res.send({ code: 501, msg: '删除图书失败' })
    }


    // res.send(`添加图书成功`)
})


//启动服务器
app.listen(7761, () => {
    console.log(`http://127.0.0.1:7761`);
})


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值