我需要将前端创建的课程添加到数据库中的courses表中,并能在前端查询到
时间: 2024-11-22 07:48:34 浏览: 15
要实现前端创建的课程添加到数据库中的 `courses` 表,并在前端查询到这些课程,你需要确保以下几个步骤:
### 1. 前端部分(Vue.js)
#### a. 创建课程表单
在 `coursedesign.vue` 文件中,已经有一个创建课程的表单。确保表单数据通过 `axios` 发送到后端。
```html
<template>
<div class="common-layout">
<el-container>
<el-aside width="130px" class="menu">
<sidermenu></sidermenu>
</el-aside>
<el-container>
<el-header>
<div class="header"></div>
</el-header>
<el-main>
<el-form :model="form" label-width="120px" style="max-width: 600px" ref="courseForm">
<el-form-item label="课程号" prop="courseId" :rules="rules.courseIdRules">
<el-input v-model="form.courseId" />
</el-form-item>
<el-form-item label="课程名" prop="courseName" :rules="rules.courseNameRule">
<el-input v-model="form.courseName" />
</el-form-item>
<el-form-item label="课时" prop="classHours" :rules="rules.classHoursRules">
<el-input v-model="form.classHours" />
</el-form-item>
<el-form-item label="上课次数" prop="classTimes" :rules="rules.classTimesRules">
<el-input v-model="form.classTimes" />
</el-form-item>
<el-form-item label="学分" prop="credits" :rules="rules.creditsRules">
<el-input v-model="form.credits" />
</el-form-item>
<el-form-item label="任课教师ID" prop="userid" :rules="rules.useridRules">
<el-input v-model="form.userid" disabled />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">创建课程</el-button>
<el-button @click="onCancel">取消</el-button>
</el-form-item>
</el-form>
</el-main>
</el-container>
</el-container>
</div>
</template>
<script lang="ts" setup>
import { reactive, ref, defineEmits } from 'vue';
import axios from 'axios';
import sidermenu from './sidermenu.vue';
const emits = defineEmits(['submit']);
const courseForm = ref(null);
const form = reactive({
courseId: '',
courseName: '',
classHours: '',
classTimes: '',
credits: '',
userid: localStorage.getItem('userid') || ''
});
const rules = {
courseIdRules: [
{ required: true, message: '课程号不能为空', trigger: 'blur' },
{ pattern: /^\d{6}$/, message: '课程号必须是6位数字', trigger: 'blur' }
],
courseNameRule: [
{ required: true, message: '课程名不能为空', trigger: 'blur' }
],
classHoursRules: [
{ required: true, message: '课时不能为空', trigger: 'blur' },
{ pattern: /^\d{2}$/, message: '课时必须是两位数字', trigger: 'blur' }
],
classTimesRules: [
{ required: true, message: '上课次数不能为空', trigger: 'blur' },
{ pattern: /^\d{2}$/, message: '上课次数必须是两位数字', trigger: 'blur' }
],
creditsRules: [
{ required: true, message: '学分不能为空', trigger: 'blur' },
{ pattern: /^\d{1}$/, message: '学分必须是1位数字', trigger: 'blur' }
],
useridRules: [
{ required: true, message: '任课教师ID不能为空', trigger: 'blur' }
]
};
const onSubmit = async () => {
if (courseForm.value) {
const valid = await courseForm.value.validate();
if (valid) {
try {
const response = await axios.post('/api/check-course-id', { courseId: form.courseId });
if (response.data.exists) {
alert('课程号已存在');
} else {
const addResponse = await axios.post('/api/add-course', form);
if (addResponse.data.message === '课程添加成功') {
alert('创建成功');
form.courseId = '';
form.courseName = '';
form.classHours = '';
form.classTimes = '';
form.credits = '';
emits('submit', form);
}
}
} catch (error) {
console.error('Error:', error);
alert('添加课程失败');
}
} else {
console.log('Validation failed');
}
}
};
const onCancel = () => {
form.courseId = '';
form.courseName = '';
form.classHours = '';
form.classTimes = '';
form.credits = '';
};
</script>
<style scoped>
.menu {
border-right: 1px solid #545c64;
height: calc(100vh);
margin-right: 0;
}
.header {
height: 100%;
border-bottom: 1px solid #545c64;
padding: 0;
margin: 0;
display: flex;
justify-content: flex-end;
align-items: center;
}
.el-header {
padding: 0;
margin: 0;
}
.el-main {
padding: 0;
}
.el-container {
padding: 0;
}
</style>
```
### 2. 后端部分(Express.js)
#### a. 添加课程接口
在 `courseSearch.js` 文件中,已经定义了 `addCourse` 函数来处理添加课程的请求。
```javascript
let db = require('../db/index');
exports.addCourse = (req, res) => {
const { courseId, courseName, classHours, classTimes, credits, userid } = req.body;
const sql = 'SELECT * FROM courses WHERE course_id = ?';
db.query(sql, [courseId], (err, results) => {
if (err) {
return res.status(500).json({ message: '数据库查询错误', error: err.message });
}
if (results.length > 0) {
return res.status(400).json({ message: '课程号已存在' });
}
const insertSql = 'INSERT INTO courses (course_id, course_name, class_hours, class_times, credits, userid) VALUES (?, ?, ?, ?, ?, ?)';
db.query(insertSql, [courseId, courseName, classHours, classTimes, credits, userid], (err, results) => {
if (err) {
return res.status(500).json({ message: '添加课程失败', error: err.message });
}
res.json({ message: '课程添加成功' });
});
});
};
```
#### b. 查询课程接口
在 `courseSearch.js` 文件中,已经定义了 `searchCourses` 函数来处理查询课程的请求。
```javascript
exports.searchCourses = (req, res) => {
const { courseName, courseId, userid } = req.body;
let sql = 'SELECT * FROM courses WHERE userid = ?';
let values = [userid];
if (courseId) {
sql += ' AND course_id = ?';
values.push(courseId);
} else if (courseName) {
sql += ' AND course_name LIKE ?';
values.push(`%${courseName}%`);
}
db.query(sql, values, (err, results) => {
if (err) {
return res.status(500).json({ message: '数据库查询错误', error: err.message });
}
if (results.length === 0) {
return res.status(404).json({ message: '没有找到任何课程' });
}
res.json(results);
});
};
```
#### c. 路由配置
在 `router.js` 文件中,已经配置了相关的路由。
```javascript
let express = require('express');
let router = express.Router();
let user = require('./api/user');
let register = require('./api/register');
let courseSearch = require('./api/courseSearch');
router.post('/user', user.post);
router.post('/register', register.post);
router.post('/api/search-courses', courseSearch.searchCourses);
router.post('/api/add-course', courseSearch.addCourse);
router.post('/api/check-course-id', courseSearch.checkCourseId);
module.exports = router;
```
### 3. 数据库部分
确保你的数据库中有 `courses` 表,并且表结构如下:
```sql
CREATE TABLE courses (
id INT AUTO_INCREMENT PRIMARY KEY,
course_id VARCHAR(6) NOT NULL UNIQUE,
course_name VARCHAR(255) NOT NULL,
class_hours INT NOT NULL,
class_times INT NOT NULL,
credits INT NOT NULL,
userid VARCHAR(255) NOT NULL
);
```
### 4. 测试
1. **添加课程**:在前端填写课程信息并提交,检查控制台是否有成功或失败的提示。
2. **查询课程**:使用查询功能,输入课程号或课程名,检查是否能查到刚刚添加的课程。
通过以上步骤,你应该能够成功地在前端创建课程并将其添加到数据库中,并能够在前端查询到这些课程。
阅读全文