利用node連接mongodb實現一個小型后端服務系統demo

http 請求

  • 實現get請求數據庫數據;
  • 實現添加數據
  • 實現編輯數據
  • 實現刪除數據
  • 實現導出txt文件、Excel文件
  • 實現查詢數據庫數據并利用導出為excel文件

node 版本 16.16.0

node 版本 18.16.0 會連接 MongoDB 數據庫錯誤。

Connected to MongoDB failed MongoServerSelectionError: connect ECONNREFUSED ::1:27017
{"name": "http-node-demo","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","start": "node index.js"},"author": "","license": "ISC","type": "module","dependencies": {"body-parser": "^1.20.2","mongodb": "^6.8.0","querystring": "^0.2.1"}
}

項目安裝 MongoDB 的 node 版本要跟啟動時的 node 版本一致,否則會報錯

const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${options.serverSelectionTimeoutMS} ms`,this.description
);

node 鏈接 MongoDB

// MongoDB連接配置
const mongoConfig = {url: "mongodb://localhost:27017",dbName: "note", //數據庫名稱
};
import { MongoClient } from "mongodb";
import { mongoConfig } from "./default.js";
const mongoDB = new MongoClient(mongoConfig.url);let db;async function mainFun() {// 創建MongoDB連接try {await mongoDB.connect();console.log("Connected to MongoDB successfully");db = mongoDB.db(mongoConfig.dbName);} catch (err) {console.log("Connected to MongoDB failed", err);}
}export { mainFun, db };

接口返回的形勢

  • 返回 404
// 解析url
const urlObj = new URL(req.url, `http://${req.headers.host}`);const params = {};
const apiKey = `${urlObj.pathname}&${req.method.toLocaleLowerCase()}`;
const item = ALL_PATH.find((v) => `/${v}` == apiKey);// 找不到路由,返回404 Not Found
if (!item) {res.writeHead(404, {"Content-Type": "text/plain; charset=utf-8",}).end("Not Found");return;
}
  • 普通 JSON 字符串
import { db } from "../mongoDB/index.js";
const getUser = async () => {try {// 查詢數據集合user的所有數據并轉為數組形式const collection = await db.collection("user").find({}).toArray();let total = 0;collection.estimatedDocumentCount(function (err, count) {if (err) throw err;total = count;console.log("Estimated total number of documents: ", count);// client.close();});return {code: 200,data: {list: collection,total: total || 0,},};} catch (err) {return {code: 500,data: {list: [],total: 0,},};}
};
  • 返回文件流
import fs from "fs";
import path from "path";const __dirname = path.resolve();const downloadDocs = async () => {const promise = new Promise((resolve, reject) => {fs.readFile(__dirname + "/docs/新建文本文檔.txt", (err, data) => {if (err) {console.error(err);reject("error");return;}resolve(data);});});try {const resData = await promise;return {code: 200,data: resData,contentType: "text/plain; charset=utf-8",};} catch (err) {return {code: 500,data: "",contentType: "text/plain; charset=utf-8",};}
};const downloadNoteTemplate = async () => {try {const data = fs.readFileSync(__dirname + "/docs/Note模板.xlsx");return {code: 200,data: data,contentType: "application/vnd.ms-excel; charset=utf-8",};} catch (err) {return {code: 500,data: "",contentType: "application/vnd.ms-excel; charset=utf-8",};}
};
resData {code: 200,data: <Buffer 50 4b 03 04 0a 00 00 00 00 00 87 4e e2 40 00 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 64 6f 63 50 72 6f 70 73 2f 50 4b 03 04 14 00 00 00 08 00 87 ... 9951 more bytes>,contentType: 'text/plain; charset=utf-8'
}

響應頭

當標頭已使用 response.setHeader() 設置時,則它們將與任何傳給 response.writeHead() 的標頭合并,其中傳給 response.writeHead() 的標頭優先。

語法

response.writeHead(statusCode[, statusMessage][, headers])
response.setHeader('Content-Type', 'text/html');
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
// Returns content-type = text/plain
const server = http.createServer((req, res) => {res.setHeader("Content-Type", "text/html");res.setHeader("X-Foo", "bar");res.writeHead(200, { "Content-Type": "text/plain" });res.end("ok");
});

返回 xlsx 文件,前端下載處理

后端接口

const downloadNoteTemplate = async () => {try {const data = fs.readFileSync(__dirname + "/docs/Note模板.xlsx");return {code: 200,data: data,contentType: "application/vnd.ms-excel; charset=utf-8",};} catch (err) {return {code: 500,data: "",contentType: "application/vnd.ms-excel; charset=utf-8",};}
};

前端下載處理

<Button onClick={() => {request('/download/noteTemplate',{method: 'get',{/*  */}responseType: "blob",responseEncoding: "utf8",options: {returnDirect: true, //returnDirect 直接返回接口所有信息},}).then((res) => {console.log('res',res);downloadContentFileFun('測試.xlsx',res)})
}}>下載</Button>
export const downloadContentFileFun = (filename, text) => {// 下載Excel的文件, type: "application/vnd.ms-excel"需要與后端返回的content保持一致,否則會出現無法打開的情況let blob = new Blob([text], { type: "application/vnd.ms-excel" });const element = document.createElement("a");const href = URL.createObjectURL(blob);element.href = href;element.setAttribute("download", filename);element.style.display = "none";element.click();//調用這個方法來讓瀏覽器知道不用在內存中繼續保留對這個文件的引用了。URL.revokeObjectURL(href);element.remove();
};

返回 txt 文件,前端下載處理

后端接口

const downloadDocs = async () => {const promise = new Promise((resolve, reject) => {fs.readFile(__dirname + "/docs/新建文本文檔.txt", (err, data) => {if (err) {console.error(err);reject("error");return;}resolve(data);});});try {const resData = await promise;return {code: 200,data: resData,contentType: "text/plain; charset=utf-8",};} catch (err) {return {code: 500,data: "",contentType: "text/plain; charset=utf-8",};}
};

前端下載處理

<ButtononClick={() => {request("download/homeDoc", {method: "get",responseType: "blob",responseEncoding: "utf8",options: {returnDirect: true, //returnDirect 直接返回接口所有信息},}).then((res) => {console.log("res", res);downloadContentFileFun("測試.txt", res);});}}
>下載
</Button>
export const downloadContentFileFun = (filename, text) => {// 這里的類型type改成application/vnd.ms-excel,發現也是可以正常打開的let blob = new Blob([text], { type: "text/plain; charset=utf-8" });const element = document.createElement("a");const href = URL.createObjectURL(blob);element.href = href;element.setAttribute("download", filename);element.style.display = "none";element.click();//調用這個方法來讓瀏覽器知道不用在內存中繼續保留對這個文件的引用了。URL.revokeObjectURL(href);element.remove();
};

關于前端下載文件的一些方法:https://blog.csdn.net/weixin_40119412/article/details/126980329

node 利用 excelJS 導出文件

//exportExcel\excel.js
// 導入
import ExcelJS from "exceljs";export default () => {// 創建工作薄const workbook = new ExcelJS.Workbook();// 設置工作簿屬性workbook.creator = "System";workbook.lastModifiedBy = "System";workbook.created = new Date(2024, 7, 3);workbook.modified = new Date();workbook.lastPrinted = new Date(2024, 7, 3);// 將工作簿日期設置為 1904 年日期系統workbook.properties.date1904 = true;// 在加載時強制工作簿計算屬性workbook.calcProperties.fullCalcOnLoad = true;workbook.views = [{x: 0,y: 0,width: 1000,height: 2000,firstSheet: 0,activeTab: 1,visibility: "visible",},];return workbook;
};
//exportExcel\index.js
import workbookFun from "./excel.js";export default async (data, columns, sheetName = "sheet1") => {const workbook = workbookFun();// 添加工作表const sheet = workbook.addWorksheet(sheetName);sheet.columns = columns;// 將數據添加到工作表中sheet.addRows(data);// 后端 node返回接口直接使用buffer流const bufferData = await workbook.xlsx.writeBuffer();// 瀏覽器可以利用Blob下載文件 ;node直接返回Blob會提示錯誤// const blob = new Blob([bufferData], {//   type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'// });return bufferData;
};

利用 exceljs 庫和 buffer.Blob 返回數據出錯

原因 不支持返回 Blob 格式的數據,只支持字符串類型或 Buffer or Uint8Array

(Use `node --trace-warnings ...` to show where the warning was created)ErrorCaptureStackTrace(err);^TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Blob

MongoDB 操作

查看集合

show collections;

返回信息

user_table
role_table

刪除一個集合


db.user_table.drop();

創建一個集合


db.createCollection('template_table')

項目源碼在gitee:https://gitee.com/yanhsama/node-http-demo

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/41558.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/41558.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/41558.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Nginx-簡介

介紹 nginx是一款HTTP和反向代理服務器、郵件代理服務器和通用TCP/IP代理服務器&#xff0c;在俄羅斯廣泛使用&#xff0c;用于代理高負載站點。 版本 nginx開源版nginx plus企業版openresty將nginx和lua腳本結合 tengine更穩定、高性能 正向代理 客戶端和代理服務是一伙的…

【vue動態組件】VUE使用component :is 實現在多個組件間來回切換

VUE使用component :is 實現在多個組件間來回切換 component :is 動態父子組件傳值 相關代碼實現&#xff1a; <component:is"vuecomponent"></component>import componentA from xxx; import componentB from xxx; import componentC from xxx;switch(…

生產力工具|viso常用常見科學素材包

一、科學插圖素材網站 一圖勝千言&#xff0c;想要使自己的論文或重要匯報更加引人入勝&#xff1f;不妨考慮利用各類示意圖和科學插圖來輔助研究工作。特別是對于新手或者繁忙的科研人員而言&#xff0c;利用免費的在線科學插圖素材庫&#xff0c;能夠極大地節省時間和精力。 …

Python字符編碼檢測利器: chardet庫詳解

Python字符編碼檢測利器: chardet庫詳解 1. chardet簡介2. 安裝3. 基本使用3.1 檢測字符串編碼3.2 檢測文件編碼 4. 高級功能4.1 使用UniversalDetector4.2 自定義編碼檢測 5. 實際應用示例5.1 批量處理文件編碼5.2 自動轉換文件編碼 6. 性能優化7. 注意事項和局限性8. 總結 在…

【代碼隨想錄】【算法訓練營】【第58天】 [卡碼110]字符串接龍 [卡碼105]有向圖的完全可達性 [卡碼106]島嶼的周長

前言 思路及算法思維&#xff0c;指路 代碼隨想錄。 題目來自 卡碼網。 day 59&#xff0c;周五&#xff0c;繼續ding~ 題目詳情 [卡碼110] 字符串接龍 題目描述 卡碼110 字符串接龍 解題思路 前提&#xff1a; 思路&#xff1a; 重點&#xff1a; 代碼實現 C語言 […

Jackson庫使用教程

1. Jackson概述 定義: Jackson是一個基于Java的開源JSON解析工具&#xff0c;用于Java對象與JSON數據的互相轉換。示例JSON:{"author": "一路向北_Coding","age": 20,"hobbies": ["coding", "leetcode", "r…

昇思25天學習打卡營第13天|linchenfengxue

Diffusion擴散模型 關于擴散模型&#xff08;Diffusion Models&#xff09;有很多種理解&#xff0c;本文的介紹是基于denoising diffusion probabilistic model &#xff08;DDPM&#xff09;&#xff0c;DDPM已經在&#xff08;無&#xff09;條件圖像/音頻/視頻生成領域取得…

小蜜蜂WMS與小蜜蜂WMS對接集成根據條件獲取客戶信息列表(分頁)連通新增客戶信息(小蜜蜂讀寫測試)

小蜜蜂WMS與小蜜蜂WMS對接集成根據條件獲取客戶信息列表&#xff08;分頁&#xff09;連通新增客戶信息(小蜜蜂讀寫測試) 接通系統&#xff1a;小蜜蜂WMS 天津市小蜜蜂計算機技術有限公司&#xff08;acbee&#xff0c;TianJinACBEEComputerTechnologyCo.,Ltd&#xff09;成立于…

基于圖像處理的滑塊驗證碼匹配技術

滑塊驗證碼是一種常見的驗證碼形式&#xff0c;通過拖動滑塊與背景圖像中的缺口進行匹配&#xff0c;驗證用戶是否為真人。本文將詳細介紹基于圖像處理的滑塊驗證碼匹配技術&#xff0c;并提供優化代碼以提高滑塊位置偏移量的準確度&#xff0c;尤其是在背景圖滑塊陰影較淺的情…

上海市計算機學會競賽平臺2023年2月月賽丙組平分數字(一)

題目描述 給定 &#x1d45b;n 個整數&#xff1a;&#x1d44e;1,&#x1d44e;2,??,&#x1d44e;&#x1d45b;a1?,a2?,?,an?&#xff0c;請判定能否將它們分成兩個部分&#xff08;不得丟棄任何數字&#xff09;&#xff0c;每部分的數字之和一樣大。 輸入格式 第…

模擬,CF 570C - Replacement

一、題目 1、題目描述 2、輸入輸出 2.1輸入 2.2輸出 3、原題鏈接 570C - Replacement 二、解題報告 1、思路分析 1、長為cnt的連續串的最小操作次數為cnt - 1 2、每次將一個非. 替換為. f要么增加1要么增加2 只有前后都是 . 的時候會增加2 同理&#xff0c;當我們將一…

STM32外擴SRAM及用法

一.概述 一般單片機有片內的RAM&#xff0c;但都不多&#xff0c;比如&#xff1a;STM32F407ZGT6 自帶了 192K 字節的 RAM&#xff0c;對一般應用來說&#xff0c;已經足夠了&#xff0c;不過在一些對內存要求高的場合&#xff0c;比如做華麗效果的 GUI&#xff0c;處理大量數據…

swagger的接口文檔導入到yapi上

一、訪問swagger接口 swagger集成到項目后&#xff0c;通過http:\\ip:port/swagger-ui.html 訪問。 說明&#xff1a;這里的路徑是基于swagger2。如果用swagger3&#xff0c;需要用swagger3的路徑進行訪問。 訪問如圖&#xff1a; 這就是swagger接口首頁。如果想導入到yapi上…

module_param_named 內核啟動時模塊參數實現原理

基于上節內核啟動參數實現原理內容, 其中對early_param的實現流程做了分析, 已基本清晰. 但有不少的參數是在內核模塊中聲明的, 具體賦值流程也值得一探究竟. nomodeset 裝過Linux系統的同學可能多少有看到過nomodeset這個參數, 解決一些顯卡點不亮Linux的問題. 那么這個nomo…

AI繪畫Stable Diffusion 新手入門教程:萬字長文解析Lora模型的使用,快速上手Lora模型!

大家好&#xff0c;我是設計師阿威 今天給大家講解一下AI繪畫Stable Diffusion 中的一個重要模型—Lora模型&#xff0c;如果還有小伙伴沒有SD安裝包的&#xff0c;可以看我往期入門教程2024最新超強AI繪畫Stable Diffusion整合包安裝教程&#xff0c;零基礎入門必備&#xff…

React Hooks --- 分享自己開發中常用的自定義的Hooks (1)

為什么要使用自定義 Hooks 自定義 Hooks 是 React 中一種復用邏輯的機制&#xff0c;通過它們可以抽離組件中的邏輯&#xff0c;使代碼更加簡潔、易讀、易維護。它們可以在多個組件中復用相同的邏輯&#xff0c;減少重復代碼。 1、useThrottle 代碼 import React,{ useRef,…

三葉青圖像識別研究簡概

三葉青圖像識別研究總概 文章目錄 前言一、整體目錄介紹二、前期安排三、構建圖像分類數據集四、模型訓練準備五、遷移學習模型六、在測試集上評估模型精度七、可解釋性分析、顯著性分析八、圖像分類部署九、樹莓派部署十、相關補充總結 前言 本系列文章為近期所做項目研究而作…

工作助手VB開發筆記(2)

今天繼續講功能 2.功能 2.9開機自啟 設置程序隨windows系統啟動&#xff0c;其實就是就是將程序加載到注冊表 Public Sub StartRunRegHKLM()REM HKEY_LOCAL_MACHINE \ SOFTWARE \ WOW6432Node \ Microsoft \ Windows \ CurrentVersion \ RunDim strName As String Applicat…

教師商調函流程詳解

作為一名教師&#xff0c;您是否曾面臨過工作調動的困惑&#xff1f;當您決定邁向新的教育環境&#xff0c;是否清楚整個商調函流程的每一個細節&#xff1f;今天&#xff0c;就讓我們一起來探討這一過程&#xff0c;確保您能夠順利地完成工作調動。 首先需要確定新調入的學校已…

裁員風波中的項目經理,如何自洽?

最近都在擔心企業裁員&#xff0c;那么項目經理會不會也有被優化的風險呢&#xff1f; 答案是&#xff0c;一定會&#xff01; 今天從3個方面給大家闡述一下項目經理崗位的發展現狀以及未來的趨勢 01 項目經理被優化的可能性大嗎&#xff1f; 02 哪一類項目經理會被最先裁員…