描述:
首先在本地搭建mysql数据库,配置:host: ‘192.168.3.249’,user: ‘mkx’,password: ‘123456’,database: ‘gg’.测试连接正常.使用express写两个接口,
1.查询所有学生的接口,使用的get请求,无参数.
2.插入一条学生信息,使用post请求,body是一个json的学生信息{name:“xxx”,age:12,score:55,s_id:1001},注:s_id是课程代号.
上代码:
数据库代码 database.js
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: '192.168.3.249',
user: 'mkx',
password: '123456',
database: 'gg'
});
const insertData = (name, age, score, s_id) => {
return new Promise((resolve, reject) => {
const query = `INSERT INTO student (name, age, score, s_id) VALUES (?, ?, ?, ?)`;
const values = [name, age, score, s_id];
connection.query(query, values, (error, results, fields) => {
if (error) {
console.error('Error occurred while inserting data:', error);
reject({ data: error })
} else {
console.log('Data inserted successfully!');
resolve({ data: results });
}
});
})
};
const getAllStudents = () => {
return new Promise((resolve, reject) => {
const query = `SELECT * FROM student`;
connection.query(query, (error, results, fields) => {
if (error) {
console.error('Error occurred while fetching data:', error);
reject({ data: error })
} else {
console.log('All students information:');
resolve({ data: results });
}
});
})
};
module.exports = { insertData, getAllStudents }
服务器代码: index.js
const express = require('express');
const database = require('./database');
const app = express();
const port = 3000;
app.use(express.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
app.post('/students', (req, res) => {
const { name, age, score, s_id } = req.body;
database.insertData(name, age, score, s_id)
.then(() => {
res.status(200).json({ message: 'Data inserted successfully!' });
})
.catch(error => {
res.status(500).json({ error: 'Error occurred while inserting data.' });
});
});
app.get('/students', (req, res) => {
database.getAllStudents()
.then(results => {
res.status(200).json(results);
})
.catch(error => {
res.status(500).json({ error: 'Error occurred while fetching data.' });
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
需要安装的依赖:
"dependencies": {
"express": "^4.18.2",
"mysql2": "^3.6.5"
}
数据库的表是个student 字段分别是 (注意:你需要自己的管理员账号,或者直接使用root账号)
id (自增的)
name 字符串
age int型的
score int型的
s_id 字符串