SoFunction
Updated on 2025-04-14

Implementation of tree structure interface development

In modern web development, data display of tree structures is very common, such as file systems, organizational structures, classification directories, etc. This article will introduce how to develop an interface that returns tree structure data in . We will use the Express framework to handle HTTP requests and use a MySQL database to store classified data.

Project Initialization

First, make sure you have installed npm and npm. Then, create a new project directory and initialize npm:

mkdir node-tree-api
cd node-tree-api
npm init -y

Next, install the required dependencies:

npm install express mysql2

Set up the database

To simplify the example, we will use the MySQL database. If you have not installed MySQL, you can download and install it from the MySQL official website.

Create a new database, such as tree_api_db:

CREATE DATABASE tree_api_db;
USE tree_api_db;

Create a classification table

Create a table named categories with the following fields:

id: The unique identifier of the classification
name: The name of the category
description: description of the classification
parent_id: parent class ID, parent_id of top-level class is NULL or 0

CREATE TABLE categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    parent_id INT DEFAULT NULL
);

Insert sample data

Insert some sample data for testing:

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);

Writing tree structure query logic

Create a file in the project directory to manage database connections:

// 
const mysql = require('mysql2');

const connection = ({
    host: 'localhost',
    user: 'your_mysql_user',
    password: 'your_mysql_password',
    database: 'tree_api_db'
});

((err) => {
    if (err) {
        ('Error connecting to the database:', );
        return;
    }
    ('Connected to the database.');
});

 = connection;

Create a file to handle the construction of a tree structure:

// 
function buildTree(categories) {
    const map = {};
    const roots = [];

    // Put each category into the map    (category => {
        map[] = { ...category, children: [] };
    });

    // Build a tree structure    (category => {
        if (category.parent_id === null || category.parent_id === 0) {
            (map[]);
        } else {
            if (map[category.parent_id]) {
                map[category.parent_id].(map[]);
            }
        }
    });

    return roots;
}

 = { buildTree };

Create Express routes

Create a file to set up the Express application and define the route:

// 
const express = require('express');
const db = require('./db');
const { buildTree } = require('./utils');

const app = express();
const port = 3000;

// Middleware, parsing JSON request body(());

// Query the classification table and return it in a tree structure('/api/categories', (req, res) => {
    const sql = "SELECT id, name, description, parent_id FROM categories";

    (sql, (err, results) => {
        if (err) {
            return (500).send({ code: 0, msg: 'Database error', data: null });
        }

        // Build a tree structure        const tree = buildTree(results);

        // Return the data of the tree structure        ({ code: 1, msg: 'Get the classification successful', data: tree });
    });
});

(port, () => {
    (`Server is running on http://localhost:${port}`);
});

Test interface

Launch your application:

node 

You can then use a tool like Postman or a browser to visit http://localhost:3000/api/categories to test the newly created interface. You should see a JSON response similar to the following:

{
    "code": 1,
    "msg": "Getting classification successful",
    "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": []
                }
            ]
        }
    ]
}

Summarize

This is the end of this article about developing tree structure interfaces. For more related contents of tree structure interfaces, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!