Assignment 1

Java你害人不浅 2025-11-06 14:30:42

832302113-伍妍欣

23124270-WuYanxin

Frontend Repository (StudentID_contacts_frontend)

|- src/
   |- index.html               # Main page displaying contact list
   |- add-contact.html         # Form for adding new contacts
   |- edit-contact.html        # Form for editing existing contacts
   |- js/
      |- api.js                # Axios configurations and API call functions
      |- index.js              # Logic for contact list rendering/operations
      |- add.js                # Logic for add contact form submission
      |- edit.js               # Logic for edit contact form handling
   |- css/
      |- style.css             # Global styling for all pages
|- README.md                   # Project description, setup, and usage guide
|- codestyle.md                # Code style standards (referencing mainstream guidelines)

Backend Repository (StudentID_contacts_backend)

|- src/
   |- controller/
      |- contactController.js  # Handles business logic for contact operations (add, edit, delete)
   |- model/
      |- contactModel.js       # Defines database schema and query functions
   |- routes/
      |- contactRoutes.js      # Maps API endpoints to controller functions
   |- config/
      |- db.js                 # Database connection configuration (e.g., MySQL)
   |- app.js                   # Entry point: initializes Express, connects routes, starts server
|- package.json                # Dependencies (Express, mysql2, etc.) and scripts
|- README.md                   # Backend setup instructions, API documentation
|- codestyle.md                # Backend code standards (referencing official guidelines)

Database Design (MySQL)

Create a contacts table to store contact information:

CREATE TABLE contacts (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,       -- Contact's full name
  phone VARCHAR(20) NOT NULL,      -- Phone number (unique constraint recommended)
  email VARCHAR(100) UNIQUE,       -- Optional: email address
  address TEXT,                    -- Optional: physical address
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Backend API Endpoints (Express Example)

  • Add Contact (POST /api/contacts)

    // controller/contactController.js
    const addContact = async (req, res) => {
      try {
        const { name, phone, email, address } = req.body;
        // Validate required fields
        if (!name || !phone) {
          return res.status(400).json({ success: false, message: "Name and phone are required" });
        }
        // Insert into database
        const result = await db.query(
          "INSERT INTO contacts (name, phone, email, address) VALUES (?, ?, ?, ?)",
          [name, phone, email || null, address || null]
        );
        res.status(201).json({ 
          success: true, 
          message: "Contact added", 
          contactId: result.insertId 
        });
      } catch (error) {
        res.status(500).json({ success: false, message: "Server error" });
      }
    };
    

    Get Contact by ID (GET /api/contacts/:id)Used for edit functionality to fetch latest data from DB

    const getContactById = async (req, res) => {
      try {
        const { id } = req.params;
        const [rows] = await db.query("SELECT * FROM contacts WHERE id = ?", [id]);
        if (rows.length === 0) {
          return res.status(404).json({ success: false, message: "Contact not found" });
        }
        res.json({ success: true, contact: rows[0] });
      } catch (error) {
        res.status(500).json({ success: false, message: "Server error" });
      }
    };

    Update Contact (PUT /api/contacts/:id)

    const updateContact = async (req, res) => {
      try {
        const { id } = req.params;
        const { name, phone, email, address } = req.body;
        
        // Fetch current contact from DB (enforce no cache)
        const [existingContact] = await db.query("SELECT * FROM contacts WHERE id = ?", [id]);
        if (existingContact.length === 0) {
          return res.status(404).json({ success: false, message: "Contact not found" });
        }
        
        // Update in database
        await db.query(
          "UPDATE contacts SET name = ?, phone = ?, email = ?, address = ? WHERE id = ?",
          [name, phone, email || null, address || null, id]
        );
        res.json({ success: true, message: "Contact updated" });
      } catch (error) {
        res.status(500).json({ success: false, message: "Server error" });
      }
    };

    Delete Contact (DELETE /api/contacts/:id)

    const deleteContact = async (req, res) => {
      try {
        const { id } = req.params;
        const [result] = await db.query("DELETE FROM contacts WHERE id = ?", [id]);
        if (result.affectedRows === 0) {
          return res.status(404).json({ success: false, message: "Contact not found" });
        }
        res.json({ success: true, message: "Contact deleted" });
      } catch (error) {
        res.status(500).json({ success: false, message: "Server error" });
      }
    };

     

  • Get All Contacts (GET /api/contacts)Fetches all contacts for frontend list display

    Frontend Implementation

  • Contact List Page (index.html)Displays all contacts in a table with "Add", "Edit", and "Delete" buttons. Uses fetch or Axios to call GET /api/contacts on load.

  • Add Contact Page (add-contact.html)A form with fields for name, phone, email, and address. On submission, sends a POST request to /api/contacts and redirects to the list page.

  • Edit Contact Page (edit-contact.html)Loads contact data by ID (via GET /api/contacts/:id), populates the form, and sends a PUT request on submission to update the contact.

...全文
52 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

164

社区成员

发帖
与我相关
我的任务
社区描述
2501_MU_SE_FZU
软件工程 高校
社区管理员
  • FZU_SE_LQF
  • 助教_林日臻
  • 朱仕君
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧