当前位置:   article > 正文

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

node api服务器

 原代码步骤

1.下载第三方包 then-fs

npm i then-fs

2.引入JSON文件

原代码

  1. // 需求: es6模块化,用async、await和then-fs模块实现操作文件数据
  2. // 功能: 增删改查;
  3. // 导入对应模块
  4. import thenFs from 'then-fs';
  5. // ES6中不支持 __dirname ,所以当前这个案例还是使用相对路径;
  6. const url = './06.json';
  7. // 1.查询; - await必须出现在async修饰的函数中;
  8. export async function getData() {
  9. try {
  10. // 利用 thenFs 读取文件内容
  11. const str = await thenFs.readFile(url, 'utf-8'); // 返回的是Promise
  12. // 把str转换为数组
  13. const arr = JSON.parse(str);
  14. // 返回数组, 将来别人调用这个函数,就可以获取数组了
  15. return arr;
  16. } catch (e) {
  17. return '获取图书列表失败';
  18. }
  19. }
  20. // // 测试获取
  21. // getData().then(res => console.log(res));
  22. // 2.添加; - await必须出现在async修饰的函数中;
  23. export async function addData(obj) {
  24. // 先读取文件中的数据
  25. const arr = await getData();
  26. // 然后向数组中添加元素
  27. obj.id = arr[arr.length - 1].id * 1 + 1;
  28. arr.push(obj);
  29. // 写入数据
  30. try {
  31. // 代码 thenFs.writeFile()之前最好写await,有阻塞功能;
  32. await thenFs.writeFile(url, JSON.stringify(arr));
  33. return '添加成功';
  34. } catch (e) {
  35. return '添加失败';
  36. }
  37. }
  38. // // 测试添加
  39. // addData({
  40. // bookname: '三体', author: '刘慈欣', publisher: '武汉人民出版社'
  41. // }).then(res => console.log(res));
  42. // 3.删除; - await必须出现在async修饰的函数中;
  43. export async function delData(id) {
  44. // 先读取文件中的数据
  45. const arr = await getData();
  46. // 过滤模拟删除功能
  47. const newArr = arr.filter(item => item.id != id);
  48. // 写入文件
  49. try {
  50. // 代码 thenFs.writeFile()之前最好写await,有阻塞功能;
  51. await thenFs.writeFile(url, JSON.stringify(newArr));
  52. return '删除成功';
  53. } catch (e) {
  54. return '删除失败';
  55. }
  56. }
  57. // // 测试删除
  58. // delData(5).then(res => console.log(res));
  59. // 4.修改;
  60. export async function putData(obj) {
  61. // 先读取文件中的数据
  62. const arr = await getData();
  63. // 修改 - 先删除,在添加
  64. const index = arr.findIndex(item => item.id == obj.id);
  65. arr.splice(index, 1, obj);
  66. // 写入数据
  67. try {
  68. // 代码 thenFs.writeFile()之前最好写await,有阻塞功能;
  69. await thenFs.writeFile(url, JSON.stringify(arr));
  70. return '修改成功';
  71. } catch (e) {
  72. return '修改失败';
  73. }
  74. }
  75. // // 测试
  76. // putData({
  77. // id: 1, bookname: '三国演义-后传',author: '罗贯东',publisher: '传智人民出版社'
  78. // }).then(res => console.log(res))
  79. // 默认导出
  80. export default { getData, addData, delData, putData }

步骤说明

1.下载第三方包 

npm i express 

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

import book from './obtain.js';

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

npm i cors

nodejs/api 查看信息

  1. import express from 'express';
  2. import btain from './obtain.js';
  3. const app = express()
  4. app.get('/aaa/bbb', async (req, res) => {
  5. const arr = await btain.getData()
  6. // 支持浏览器ajax跨域访问, * 代表任意人都可以来请求
  7. res.setHeader('Access-Control-Allow-Origin', '*')
  8. if (arr instanceof Array) {
  9. res.send({ code: 200, msg: '获取图书列表成功', data: arr })
  10. } else {
  11. res.send({ code: 501, msg: '获取图书列表失败' })
  12. }
  13. // res.send('获取图书列表成功')
  14. })
  15. // 启动 web 服务器
  16. app.listen(8080, () => {
  17. console.log(' http://127.0.0.1:8080')
  18. })

nodejs/api 添加信息

  1. import express from 'express';
  2. import book from './obtain.js';
  3. const app = express()
  4. app.use(express.urlencoded({ extended: true }))
  5. app.use(express.json())
  6. //设置全局跨域
  7. const cors = require('cors')
  8. app.use(cors())
  9. //post
  10. app.post('/ccc/ddd', async (req, res) => {
  11. const arr = await book.addData(req.body)
  12. // console.log(arr);
  13. if (arr == '添加成功') {
  14. res.send({ code: 201, msg: '添加图书成功' })
  15. } else {
  16. res.send({ code: 501, msg: '添加图书失败' })
  17. }
  18. // res.send(`添加图书成功`)
  19. })
  20. //启动服务器
  21. app.listen(5521, () => {
  22. console.log(`http://127.0.0.1:5521`);
  23. })


 

nodejs/api 删除信息

  1. import express from 'express';
  2. import book from './obtain.js';
  3. const app = express()
  4. app.use(express.urlencoded({ extended: true }))
  5. app.use(express.json())
  6. //设置全局跨域
  7. const cors = require('cors')
  8. app.use(cors())
  9. //post DELETE
  10. app.delete('/eee/fff', async (req, res) => {
  11. res.set('Access-Control-Allow-Origin', "*"); // 设置响应头
  12. const arr = await book.delData(req.query.id)
  13. console.log(arr);
  14. if (arr == '删除成功') {
  15. res.send({ code: 201, msg: '删除图书成功' })
  16. } else {
  17. res.send({ code: 501, msg: '删除图书失败' })
  18. }
  19. // res.send(`添加图书成功`)
  20. })
  21. //启动服务器
  22. app.listen(7761, () => {
  23. console.log(`http://127.0.0.1:7761`);
  24. })


 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/68985
推荐阅读
相关标签
  

闽ICP备14008679号