EE308FZ Assignment 2 Back-end separation calculator programming

EE308FZ Assignment 2 Back-end separation calculator programming

EE308FZ main ClassHere
The Link of Requirement of This AssignmentAssignment 2 Requirement
Front-end code linkGithub
back-end code linkGithub
The Aim of Lab 1Back-end separation calculator programming
MU STU ID and FZU STU ID21124833_832101217

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 StagesEstimated Time(minutes)Actual Time(minutes)
Planning
• Estimate120120
Development
• Analysis6080
• Design Spec5045
• Design Review1015
• Coding Standard1510
• Design6080
• Coding200230
• Code Review100150
• Test120180
Reporting
• Test Repor1520
• Size Measurement3020
• Postmortem & Process Improvement Plan4545
Sum825995

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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值