EE308FZ Assignment 2 Back-end separation calculator programming
EE308FZ main Class | Here |
---|---|
The Link of Requirement of This Assignment | Assignment 2 Requirement |
Front-end code link | Github |
back-end code link | Github |
The Aim of Lab 1 | Back-end separation calculator programming |
MU STU ID and FZU STU ID | 21124833_832101217 |
Catalogue
1 Introduction
This blog will introduce the development of WeChat calculator applet from three aspects.
-
Front-end development: Use native mode to build the front-end of a small program calculator. This will include things like creating pages, processing user input, presenting calculation results, and more.
-
Bank-end development:Use Node.js and the Express framework to build a simple backend service that handles the request of the applet and stores the calculation results and connects the history to the MongoDB database.
-
Communication between front-end and back-end: sending requests, processing responses, and ensuring data security and integrity.
-
Back-end development process display
-
Finished product display
-
Your can see the complete code on github
2 PSP Table
Personal Software Process Stages | Estimated Time(minutes) | Actual Time(minutes) |
---|---|---|
Planning | ||
• Estimate | 120 | 120 |
Development | ||
• Analysis | 60 | 80 |
• Design Spec | 50 | 45 |
• Design Review | 10 | 15 |
• Coding Standard | 15 | 10 |
• Design | 60 | 80 |
• Coding | 200 | 230 |
• Code Review | 100 | 150 |
• Test | 120 | 180 |
Reporting | ||
• Test Repor | 15 | 20 |
• Size Measurement | 30 | 20 |
• Postmortem & Process Improvement Plan | 45 | 45 |
Sum | 825 | 995 |
3 Design implementation process
-
This WeChat calculator applet development flow chart
-
Developing a backend that can store data for the WeChat calculator applet is the key to this assignment. I chose express and Node.js to build the backend server, store the history records in the MongoDB database, and use WeChat to provide the frontend The network request wx.request API is used to make HTTP requests to the backend.
4 Critical code description
4.1 Front end
- In order to realize the scientific computing function, the code is modified as follows based on the first operation
Page({
data: {
num: '',
op: '',
},
result: null,
isClear: false,
numBtn: function (e) {
var num = e.target.dataset.val;
if (this.data.num === '0' || this.isClear) {
this.setData({ num: num });
this.isClear = false;
} else {
this.setData({ num: this.data.num + num });
}
},
opBtn: function (e) {
var op = this.data.op;
var num = Number(this.data.num);
var val = e.target.dataset.val;
if (val === '/') {
this.setData({ op: '÷' });
} else if (val === '*') {
this.setData({ op: '×' });
} else if (val === '%') {
num = num / 100;
this.setData({ num: num.toString(), op: '' });
return;
} else if (val === 'sin') {
num = Math.sin(num * (Math.PI / 180));
this.setData({ num: num.toString(), op: '' });
return;
} else if (val === 'cos') {
num = Math.cos(num * (Math.PI / 180));
this.setData({ num: num.toString(), op: '' });
return;
} else if (val === 'tan') {
num = Math.tan(num * (Math.PI / 180)); // 将角度转换为弧度
this.setData({ num: num.toString(), op: '' });
return;
} else if (val === '^') {
this.setData({ op: '^' });
} else if (val === '√') {
num = Math.sqrt(num);
this.setData({ num: num.toString(), op: '' });
return;
} else if (op === 'mod') { // 执行取余数运算
num = num % this.data.num;
this.setData({ num: num.toString(), op: '' });
} else {
this.setData({ op: val });
}
if (this.isClear) {
return;
}
this.isClear = true;
if (this.result === null || this.result === undefined) {
this.result = num;
return;
}
if (op === '+') {
this.result = this.result + num;
} else if (op === '-') {
this.result = this.result - num;
} else if (op === '×') {
this.result = (this.result * num).toFixed();
} else if (op === '÷') {
this.result = this.result / num;
} else if (op === '^') {
this.result = Math.pow(this.result, num);
}
this.setData({ num: this.result.toString() });
},
dotBtn: function () {
if (this.isClear) {
this.setData({ num: '0.' });
this.isClear = false;
return;
}
if (this.data.num.indexOf('.') >= 0) {
return;
}
this.setData({ num: this.data.num + '.' });
},
delBtn: function () {
var temp = this.data.num.toString();
var num = temp.substr(0, this.data.num.length - 1);
this.setData({ num: num === '' ? '0' : num });
},
resetBtn: function () {
this.result = null;
this.isClear = false;
this.setData({ num: '0', op: '' });
},
//科学计算器
numBtn: function (e) {
var num = e.target.dataset.val;
if (this.data.num === '0' || this.isClear) {
this.setData({ num: num });
this.isClear = false;
} else {
this.setData({ num: this.data.num + num });
}
},
// ...
logBtn: function () {
// 计算以 10 为底的对数
var num = Number(this.data.num);
if (num > 0) {
num = Math.log10(num);
this.setData({ num: num.toString() });
} else {
// 处理无效输入
console.error('Invalid input for log');
}
},
lnBtn: function () {
// 计算自然对数
var num = Number(this.data.num);
if (num > 0) {
num = Math.log(num);
this.setData({ num: num.toString() });
} else {
// 处理无效输入
console.error('Invalid input for ln');
}
},
reciprocalBtn: function () {
var num = Number(this.data.num);
if (num !== 0) {
num = 1 / num;
this.setData({ num: num.toString() });
} else {
// 处理除以零错误
console.error('Division by zero');
}
},
navigateToNewPage: function () {
wx.navigateTo({
url: '/pages/history/history', // 新页面的路径
});
},
})
- Here we mainly show the request back-end interface
Page({
data: {
history: [], // Used to store historical records
},
onLoad: function () {
this.fetchHistory();
},
fetchHistory: function () {
//Get the history from the back-end server
wx.request({
url: 'http://localhost:3000/history ;
method: 'GET',
success: (res) => {
if (res.statusCode === 200) {
this.setData({ history: res.data });
} else {
console.error('Failed to fetch history');
}
},
fail: (err) => {
console.error(err);
},
});
},
});
4.2 Back-end
Create an Express application
- WeChat applet backend written using Node.js and Express framework. The provided HTTP routes are used for data storage respectively. Connect to a MongoDB database to persist data.
- Dependent libraries such as Express, Mongoose (for MongoDB database connection) and Body Parser (for parsing HTTP request bodies).Create an Express application instance and specify the port number 3000 where the server is running.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// Connect to MongoDB database
mongoose.connect('mongodb://localhost/calculator', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
//Create data model
const Calculation = mongoose.model('Calculation', {
expression: String,
result: String,
});
app.use(bodyParser.json());
//Handle storage of calculation results
app.post('/store-calculation', async (req, res) => {
const { expression, result } = req.body;
const calculation = new Calculation({ expression, result });
try {
await calculation.save();
res.status(201).json({ message: 'Calculation stored successfully' });
} catch (err) {
res.status(500).json({ error: 'Error storing calculation' });
}
});
// Get history
app.get('/history', async (req, res) => {
try {
const history = await Calculation.find().exec();
res.json(history);
} catch (err) {
res.status(500).json({ error: 'Error fetching history' });
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
The back-end server starts
Enter node server.js in the control terminal of VScode. This will start an Express server listening on port 3000. Enables Express applications to receive front-end requests and store history.
Database visualization
Navicat is connected to the MongoDB database. Navicat can clearly and intuitively display the historical records stored in the database.
5 Final effect demonstration
IMPORTANT REQUIREMENTS View history functionality
Complete function implementation:
including basic operations,scientific operations, and viewing history records
7 Summary
This development process covers the front-end and back-end development of the WeChat applet and interaction with the MongoDB database. A simple server was built using Node.js and the Express framework on the backend to handle the HTTP requests sent by the front-end of the mini program. We connected the MongoDB database and created a data model to store the calculation history. This backend service implements the functions of storing calculation results and obtaining history records, and processes data through HTTP routing and the Mongoose library.