170
社区成员




目录
一、Git repository links and code standards links
五、Design and implementation process
The course for this assignment | Front-end and back-end separate contact programming |
homework requirement | Basic code and release |
The objective of this task |
Implement basic address book functions |
References | first assignment |
GitHub存储库:kelis21/kelis21
---
modules | Estimated time (hour) | Actual time (time) |
demand analysis | 1 | 1 |
Finalizing Functional Design | 2 | 2 |
design | 2 | 3 |
interfacial design | 2 | 4 |
Database Desig | 5 | 6 |
coding | ||
front-end module | 20 | 32 |
database module | 21 | 44 |
Project summary and improvement | 1 | 2 |
Front page display
Add Student Information
change information
Delete messages
The message is not filled in
The code is as follows:
// 1. 读取本地存储的数据 student-data 本地存储的命名
const data = localStorage.getItem('student-data')
// 2. 如果有就返回对象,没有就声明一个空的数组
const arr = data ? JSON.parse(data) : []
const tbody = document.querySelector('tbody')
// 3. 渲染模块函数
function render() {
const trArr = arr.map(function (item, i) {
return `
<tr>
<td>${item.uname}</td>
<td>${item.age}</td>
<td>${item.phone}</td>
<td>
<a href="javascript:" data-id=${i}>删除</a>
</td>
<td>
<a href="javascript:" data-id=${i}>修改</a>
</td>
</tr>
`
})
tbody.innerHTML = trArr.join('')
}
render()
// 4. 录入模块
const info = document.querySelector('.info')
const items = info.querySelectorAll('[name]')
info.addEventListener('submit', e => {
e.preventDefault()
let valid = true
const obj = {}
items.forEach(item => {
if (!item.value.trim()) {
valid = false
alert('所有字段都是必填的')
return false
}
obj[item.name] = item.value
if (!valid) return
})
fetch('students', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ obj, stuId: generateStudentId(arr) })
})
.then(response => response.json())
.then(data => {
if (data.success) {
arr.push({ ...obj, stuId: data.stuId })
localStorage.setItem('student-data', JSON.stringify(arr))
render()
info.reset()
} else {
alert('添加学生失败' + data.message)
}
})
.catch(error => {
const errorMessage = error.message || '未知错误' // 提供默认错误消息
console.log('error', errorMessage)// 在控制台打印错误信息
alert(`添加学生时发生错误: ${errorMessage}`) // 显示包含错误消息的警告框
})
for (let i = 0; i < items.length; i++) {
const item = items[i]
if (items[i].value === '') {
return alert('输入内容不能为空')
}
obj[item.name] = item.value
}
// 追加给数组
arr.push(obj)
localStorage.setItem('student-data', JSON.stringify(arr))
// 渲染页面
render()
// 重置表单
info.reset()
})
function generateStudentId(arr) {
return arr.length ? arr[arr.length - 1].stuId + 1 : 1
}
// 5. 删除与修改模块
tbody.addEventListener('click', e => {
if (e.target.tagName === 'A') {
const action = e.target.textContent
const index = parseInt(e.target.dataset.id, 10)
const rowData = arr[index]
if (!isNaN(index) && rowData) {
if (action === '删除') {
fetch(`students/${arr[index].stuId}`, {
method: 'DELETE'
})
.then(response => response.json())
.then(data => {
if (data.success) {
arr.splice(index, 1)
localStorage.setItem('student-data', JSON.stringify(arr))
render()
} else {
alert('删除学生失败: ' + data.message)
}
})
.catch(error => {
console.error('删除学生时发生错误:', error)
alert('删除学生时发生错误')
})
} else if (action === '修改') {
// 显示模态框
document.getElementById('modal').style.display = 'block'
// 填充表单数据
document.getElementById('uname').value = rowData.uname
document.getElementById('age').value = rowData.age
document.getElementById('phone').value = rowData.phone
// 监听表单提交事件
document.getElementById('editForm').addEventListener('submit', function (event) {
event.preventDefault(); // 阻止默认提交行为
// 获取新数据
const newName = document.getElementById('uname').value
const newAge = parseInt(document.getElementById('age').value, 10)
const newPhone = parseInt(document.getElementById('phone').value, 10)
// 更新数组中的数据
arr[index] = { uname: newName, age: newAge, phone: newPhone }
// 保存数据到localStorage并重新渲染表格
localStorage.setItem('student-data', JSON.stringify(arr))
render()
fetch(`students`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ uname: newName, age: newAge, phone: newPhone })
})
.then(response => response.json())
.then(data => {
if (data.success) {
arr[index] = { uname: newName, age: newAge, phone: newPhone }
localStorage.setItem('student-data', JSON.stringify(arr))
render()
closeModal()
} else {
alert('更新学生失败: ' + data.message)
}
})
.catch(error => {
console.error('更新学生时发生错误:', error)
alert('更新学生时发生错误')
})
// 关闭模态框
closeModal()
})
}
localStorage.setItem('student-data', JSON.stringify(arr))
render()
}
}
})
// 关闭模态框的函数
function closeModal() {
document.getElementById('modal').style.display = 'none'
}
const express = require('express')
const mysql = require('mysql')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const port = 3000
app.use(cors())
// 设置MySQL连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'shaocan21',
database: 'students'
})
connection.connect()
// 中间件:解析JSON请求体
app.use(bodyParser.json())
// 路由:处理POST请求以添加学生
app.post('/students', (req, res) => {
const { uname, age, phone } = req.body;
let stuId = 1; // 简单的示例,实际中需要从数据库中获取最大ID并加1
const query = 'SELECT MAX(stuId) AS maxId FROM students';
connection.query(query, (error, results) => {
if (error) throw error;
if (results[0] && results[0].maxId) {
stuId = results[0].maxId + 1;
}
// 插入新学生到数据库
const sql = 'INSERT INTO students (uname, age, phone) VALUES ( ?, ?, ?)';
connection.query(sql, [uname, age, phone,], (error, results) => {
if (error) throw error;
res.json({ success: true, stuId: stuId }); // 返回新生成的stuId给前端
})
})
})
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`)
})
1 Demand Analysis:
Determine that you need to build a back-end API service to handle adding, deleting, correcting and checking student information.
Decide to use the Express framework to build the server and MySQL as the database to store student information.
Determine the API's routing and request methods, such as POST for adding students, GET for getting a list of students, and so on.
2. Technology selection:
Server framework:Express
database:MySQL
Request body resolution:body-parser
Cross-domain request processing:cors
Asynchronous programming:async/await
3.DBD:
Create a database called students.
Create a students table in the students database with fields stuId (student ID, primary key, increment), uname (user name), age (age), and phone (phone number).
4.API design:
/students: The POST request is used to add students.
/students/:id: GET requests are used to get student information with a specific ID, PUT requests are used to update student information, and DELETE requests are used to delete student information.
The /students: GET request (without ID) is used to get a list of all students.
5.Code structure design:
Put the database connection configuration and server startup logic in separate files.
Create a routing file that defines all student-related API routes.
Create a controller file to handle the business logic in the route.
1.Initialize the project:
Initialize the project with npm init -y.
Install dependencies such as Express, MySQL, body-parser, cors, etc.
Create databases and tables:
Create databases and tables using the MySQL command line or graphical tools.
2.Edit code:
Create a server.js file to configure the Express server, database connections, and middleware.
Create a routes folder and in it create a student.js file that defines student-related API routes.
Create a controllers folder and in it create a studentsController.js file to handle the student-related business logic.
3. Implement routing and controller:
Define the route in students.js and call the function in studentsController.js to handle the request.
Write functions in studentsController.js to handle the logic for adding, getting, updating, and deleting students.
4. Test API:
Test API functionality using Postman or similar tools.
Ensure that all apis correctly return the expected results.