Back-end separation calculator programming

I. Introduction

This task is based on the EE308 first work Visual Calculator to separate the front and back ends, save historical calculation results through interaction, and obtain the latest 10 results.

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617378696
The Aim of This AssignmentBack-end separation calculator programming
MU STU ID and FZU STU IDMU ID 21126640 & FZU ID 832101104

Link to finished project code: https://github.com/SuJob1/Calculator/blob/main/

II. Link to the finished project code

https://github.com/SuJob1/Back-end-separation-calculator/tree/front-end
https://github.com/SuJob1/Back-end-separation-calculator/tree/back-end

III. PSP form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning3045
• Estimate3045
Development870755
• Analysis6070
• Design Spec4030
• Design Review3020
• Coding Standard2015
• Design7050
• Coding350300
• Code Review10070
• Test200250
Reporting100130
• Test Report5085
• Size Measurement3025
• Postmortem & Process Improvement Plan2020
Sum1000930

IV. Display of finished products

请添加图片描述

V. Design and Implementation Process

5.1. Design

5.1.1 Front-end

On the basis of realizing the function of the original calculator, I added the remainder %, logarithm log and exponential powere^ operation, and reformatted the whole button distribution. In addition, the historical query function is added, and a separate table is designed to store historical data on the right side of calculation.

5.1.2 Back-end

Since the function implementation of my front-end code is completed by JavaScript, I choose to use node.js as the back-end development platform and use the express framework for development. Considering that the contents stored in the calculator are relatively simple, I choose to use the lightweight database SQLite to store data.

5.2. Implementation

5.2.1 HTML Structure:

  • Form Structure: Add the table to store history data.

  • Input Elements: Add the button of remainder %, logarithm log, exponential powere^ and history History.

5.2.2 CSS Styling:
  • Table: Design the color and position of the table.
5.2.3 JavaScript Logic:
  • Calculation: Add new functions to calculate remainder %, logarithm log and exponential powere^.
  • Interaction: (a) Add new functions saveCalculation to save the formula and results and send them to the server in the back end. (b) Obtain the results of the last 10 calculations from the server in the back end.
5.2.4 node.js:
  • database Create and initialize the table format of the database.
  • Save Get user revenue from the front end and save the results to the database.
  • Obtain Return the result from the database to the front-end display.

5.3. Flow Chart:

VI. Code description

请添加图片描述

  • Table design for history records
        <table id="calculationsTable">
                <thead>
                    <tr>
                        <th>formula</th>
                        <th>result</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Calculation history will be displayed here -->
                </tbody>
            </table>

This section creates the contents of the table.

  /* Calculations table styling */
    #calculationsTable {
        position: absolute;
        width: 300px;
        margin-left: 600px;
        margin-top: 100px;
        border-collapse: collapse;
    }

    #calculationsTable th, #calculationsTable td {
        padding: 8px;
        border: 1px solid #ddd;
    }

    #calculationsTable th {
        background-color: #f2f2f2;
        color: black;
    }

    #calculationsTable tr:hover {
        background-color: #ddd;
    }

This section creates the style of the table such as color, font size, and placement.

  • Operation of remainder, logarithm and exponential power
        value = value.replace(/log(\d+)\((\d+)\)/g, function(match, base, number) {
        return Math.log(number) / Math.log(base);
        });
        value = value.replace(/e\^(\d+)/g, function(match, exponent) {
        return Math.pow(Math.E, Number(exponent));
        });
        value = value.replace(/(\d+)%(\d+)/g, function(match, firstValue, secondValue) {
        return Number(firstValue) % Number(secondValue);
        });

These 3 pieces of code are handling exponentials and logarithms and exponentials, converting them into actual numerical calculations, and replacing the results back into the original string.

  • Front-end interaction
    function saveCalculation(formula, result) {
        fetch('http://localhost:3000/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ formula, result })
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                console.error('Error saving result:', data.error);
            }
        });
    }

    // New function: Get the results of the last 10 calculations
    function fetchRecentCalculations() {
        fetch('http://localhost:3000/recent')
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById("calculationsTable").getElementsByTagName("tbody")[0];
                tableBody.innerHTML = "";
                data.forEach(calculation => {
                    const newRow = tableBody.insertRow();
                    newRow.insertCell(0).innerText = calculation.formula;
                    newRow.insertCell(1).innerText = calculation.result;
                });
            });
    }

These two functions are used to obtain the Api interface of the back end and convert the data into Json format to pass to the back end to realize the writing and reading of the database.

  • Back-end interaction
const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3');
const cors = require('cors');
const app = express();
app.use(cors());
const db = new sqlite3.Database('calculations.db');

app.use(bodyParser.json());

// Initialize the database
db.serialize(() => {
    db.run("CREATE TABLE IF NOT EXISTS calculations (formula TEXT, result TEXT)");
});

// Save the calculation result to the database
app.post('/save', (req, res) => {
    const formula = req.body.formula;
    const result = req.body.result;
    db.run("INSERT INTO calculations (formula, result) VALUES (?, ?)", [formula, result], (err) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        res.json({ success: true });
    });
});

// Obtain the latest 10 calculation results
app.get('/recent', (req, res) => {
    db.all("SELECT formula, result FROM calculations ORDER BY rowid DESC LIMIT 10", [], (err, rows) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        res.json(rows);
    });
});


const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

  • Importing Required Modules: The code uses the require statements to import modules like Express, Body Parser, SQLite3, and CORS.

  • Creating an Express App: An Express application is created using express(), and it initializes an SQLite3 database to store calculation history.

  • Setting Up CORS Middleware: The app.use(cors()) middleware is used to enable Cross-Origin Resource Sharing (CORS), allowing cross-domain requests.

  • Initializing Database Table: A table named “calculations” is created in the SQLite3 database to store the formula and result of calculations.

  • Defining an API Endpoint to Save Calculation Results: The code defines a POST request endpoint using app.post(‘/save’, …), which is used to save calculation results to the database.

  • Defining an API Endpoint to Retrieve Recent Calculation Results: A GET request endpoint is defined with app.get(‘/recent’, …), which retrieves the ten most recent calculation history records.

  • Starting the Server: The server is started using app.listen(PORT, …), and it listens on port 3000. The server address is displayed in the console.

VII. Summary

In this practice, I have learned a lot of back-end related knowledge and code writing, and I will use some simple databases to complete tasks through back-end interaction.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值