Node.js中開(kāi)發(fā)樹(shù)形結(jié)構(gòu)接口的實(shí)現(xiàn)
在現(xiàn)代 Web 開(kāi)發(fā)中,樹(shù)形結(jié)構(gòu)的數(shù)據(jù)展示非常常見(jiàn),例如文件系統(tǒng)、組織架構(gòu)、分類(lèi)目錄等。本文將介紹如何在 Node.js 中開(kāi)發(fā)一個(gè)返回樹(shù)形結(jié)構(gòu)數(shù)據(jù)的接口。我們將使用 Express 框架來(lái)處理 HTTP 請(qǐng)求,并使用 MySQL 數(shù)據(jù)庫(kù)來(lái)存儲(chǔ)分類(lèi)數(shù)據(jù)。
項(xiàng)目初始化
首先,確保你已經(jīng)安裝了 Node.js 和 npm。然后,創(chuàng)建一個(gè)新的項(xiàng)目目錄并初始化 npm:
mkdir node-tree-api cd node-tree-api npm init -y
接下來(lái),安裝所需的依賴(lài)包:
npm install express mysql2
設(shè)置數(shù)據(jù)庫(kù)
為了簡(jiǎn)化示例,我們將使用 MySQL 數(shù)據(jù)庫(kù)。如果你還沒(méi)有安裝 MySQL,可以從 MySQL 官方網(wǎng)站 下載并安裝。
創(chuàng)建一個(gè)新的數(shù)據(jù)庫(kù),例如 tree_api_db:
CREATE DATABASE tree_api_db; USE tree_api_db;
創(chuàng)建分類(lèi)表
創(chuàng)建一個(gè)名為 categories 的表,包含以下字段:
id: 分類(lèi)的唯一標(biāo)識(shí)
name: 分類(lèi)的名稱(chēng)
description: 分類(lèi)的描述
parent_id: 父分類(lèi)的 ID,頂級(jí)分類(lèi)的 parent_id 為 NULL 或 0
CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
parent_id INT DEFAULT NULL
);
插入示例數(shù)據(jù)
插入一些示例數(shù)據(jù)以便測(cè)試:
INSERT INTO categories (name, description, parent_id) VALUES
('Electronics', 'Electronic products', NULL),
('Computers', 'Computer products', 1),
('Laptops', 'Laptop computers', 2),
('Desktops', 'Desktop computers', 2),
('Mobile Phones', 'Mobile phones', 1),
('Smartphones', 'Smart mobile phones', 5),
('Feature Phones', 'Feature mobile phones', 5),
('Tablets', 'Tablet devices', 1);
編寫(xiě)樹(shù)形結(jié)構(gòu)查詢(xún)邏輯
在項(xiàng)目目錄中創(chuàng)建一個(gè) db.js 文件來(lái)管理數(shù)據(jù)庫(kù)連接:
// db.js
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_mysql_user',
password: 'your_mysql_password',
database: 'tree_api_db'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.stack);
return;
}
console.log('Connected to the database.');
});
module.exports = connection;創(chuàng)建一個(gè) utils.js 文件來(lái)處理樹(shù)形結(jié)構(gòu)的構(gòu)建:
// utils.js
function buildTree(categories) {
const map = {};
const roots = [];
// 將每個(gè)分類(lèi)放入 map 中
categories.forEach(category => {
map[category.id] = { ...category, children: [] };
});
// 構(gòu)建樹(shù)形結(jié)構(gòu)
categories.forEach(category => {
if (category.parent_id === null || category.parent_id === 0) {
roots.push(map[category.id]);
} else {
if (map[category.parent_id]) {
map[category.parent_id].children.push(map[category.id]);
}
}
});
return roots;
}
module.exports = { buildTree };創(chuàng)建 Express 路由
創(chuàng)建一個(gè) app.js 文件來(lái)設(shè)置 Express 應(yīng)用并定義路由:
// app.js
const express = require('express');
const db = require('./db');
const { buildTree } = require('./utils');
const app = express();
const port = 3000;
// 中間件,解析 JSON 請(qǐng)求體
app.use(express.json());
// 查詢(xún)分類(lèi)表并以樹(shù)形結(jié)構(gòu)返回
app.get('/api/categories', (req, res) => {
const sql = "SELECT id, name, description, parent_id FROM categories";
db.query(sql, (err, results) => {
if (err) {
return res.status(500).send({ code: 0, msg: 'Database error', data: null });
}
// 構(gòu)建樹(shù)形結(jié)構(gòu)
const tree = buildTree(results);
// 返回樹(shù)形結(jié)構(gòu)的數(shù)據(jù)
res.send({ code: 1, msg: '獲取分類(lèi)成功', data: tree });
});
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});測(cè)試接口
啟動(dòng)你的 Node.js 應(yīng)用:
node app.js
然后,你可以使用工具如 Postman 或?yàn)g覽器訪問(wèn) http://localhost:3000/api/categories 來(lái)測(cè)試新創(chuàng)建的接口。你應(yīng)該會(huì)看到類(lèi)似以下的 JSON 響應(yīng):
{
"code": 1,
"msg": "獲取分類(lèi)成功",
"data": [
{
"id": 1,
"name": "Electronics",
"description": "Electronic products",
"parent_id": null,
"children": [
{
"id": 2,
"name": "Computers",
"description": "Computer products",
"parent_id": 1,
"children": [
{
"id": 3,
"name": "Laptops",
"description": "Laptop computers",
"parent_id": 2,
"children": []
},
{
"id": 4,
"name": "Desktops",
"description": "Desktop computers",
"parent_id": 2,
"children": []
}
]
},
{
"id": 5,
"name": "Mobile Phones",
"description": "Mobile phones",
"parent_id": 1,
"children": [
{
"id": 6,
"name": "Smartphones",
"description": "Smart mobile phones",
"parent_id": 5,
"children": []
},
{
"id": 7,
"name": "Feature Phones",
"description": "Feature mobile phones",
"parent_id": 5,
"children": []
}
]
},
{
"id": 8,
"name": "Tablets",
"description": "Tablet devices",
"parent_id": 1,
"children": []
}
]
}
]
}
總結(jié)
到此這篇關(guān)于Node.js中開(kāi)發(fā)樹(shù)形結(jié)構(gòu)接口的文章就介紹到這了,更多相關(guān)Node.js 樹(shù)形結(jié)構(gòu)接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MySQL如何查找樹(shù)形結(jié)構(gòu)中某個(gè)節(jié)點(diǎn)及其子節(jié)點(diǎn)
- MySQL查詢(xún)樹(shù)形結(jié)構(gòu)數(shù)據(jù)的兩種方法
- MySQL中的常用樹(shù)形結(jié)構(gòu)設(shè)計(jì)總結(jié)
- MySql樹(shù)形結(jié)構(gòu)(多級(jí)菜單)查詢(xún)?cè)O(shè)計(jì)方案
- Mysql樹(shù)形結(jié)構(gòu)的數(shù)據(jù)庫(kù)表設(shè)計(jì)方案
- PostgreSQL樹(shù)形結(jié)構(gòu)的遞歸查詢(xún)示例
- sqlserver 樹(shù)形結(jié)構(gòu)查詢(xún)單表實(shí)例代碼
- SQL處理多級(jí)分類(lèi),查詢(xún)結(jié)果呈樹(shù)形結(jié)構(gòu)
相關(guān)文章
nodejs redis 發(fā)布訂閱機(jī)制封裝實(shí)現(xiàn)方法及實(shí)例代碼
這篇文章主要介紹了nodejs redis 發(fā)布訂閱機(jī)制封裝的相關(guān)資料,這里提供了實(shí)現(xiàn)方法,及實(shí)例代碼,具有參考價(jià)值,需要的朋友可以參考下2016-12-12
手把手教你用Node.js爬蟲(chóng)爬取網(wǎng)站數(shù)據(jù)的方法
這篇文章主要介紹了手把手教你用Node.js爬蟲(chóng)爬取網(wǎng)站數(shù)據(jù),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
輕松創(chuàng)建nodejs服務(wù)器(6):作出響應(yīng)
這篇文章主要介紹了輕松創(chuàng)建nodejs服務(wù)器(6):作出響應(yīng),我們接著改造服務(wù)器,讓請(qǐng)求處理程序能夠返回一些有意義的信息,需要的朋友可以參考下2014-12-12
TypeScript開(kāi)發(fā)Node.js程序的方法
這篇文章主要介紹了TypeScript開(kāi)發(fā)Node.js程序的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
nodejs根據(jù)ip數(shù)組在百度地圖中進(jìn)行定位
本文主要介紹了nodejs根據(jù)ip數(shù)組在百度地圖中進(jìn)行定位的方法,具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-03-03
NodeJS多種創(chuàng)建WebSocket監(jiān)聽(tīng)的方式(三種)
這篇文章主要介紹了NodeJS多種創(chuàng)建WebSocket監(jiān)聽(tīng)的方式,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06

