创建数据库和表结构
CREATE DATABASE collect;
USE collect;
CREATE TABLE `info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`create_date` bigint(20) DEFAULT NULL COMMENT '时间',
`type` varchar(20) DEFAULT NULL COMMENT '数据分类',
`text_value` text COMMENT '内容',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4
创建前端项目
mkdir node-mysql-api
cd node-mysql-api
npm init -y
npm install express mysql cors
新建server.js
文件,保存以下内容
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const app = express();
const port = 3000;
// 使用中间件解析JSON请求体
app.use(express.json());
// 使用CORS中间件
app.use(cors());
// 创建MySQL连接
const db = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'collect', // 替换为你的数据库用户名
password: '123456',// 替换为你的数据库密码
database: 'collect'
});
// 连接到数据库
db.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
return;
}
console.log('Connected to the database');
});
// 定义saveInfo接口
app.post('/saveInfo', (req, res) => {
const { createDate = (new Date()).getTime(), type, textValue } = req.body;
if (!type || !textValue) {
return res.status(400).send({code: 0, message:'All fields are required'});
}
const sql = 'INSERT INTO info (create_date, type, text_value) VALUES (?, ?, ?)';
const values = [createDate, type, textValue];
db.query(sql, values, (err, results) => {
if (err) {
console.error('Error inserting data:', err);
return res.status(500).send('Server error');
}
res.status(200).send({code: 1, message: "Info saved with ID: "+results.insertId});
});
});
// 方便测试用
app.get('/',(req,res)=>{
res.send('<h1>hello world</h1>')
})
// 启动服务器
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
启动服务器
node server.js
在浏览器中打开:http://localhost:3000,可以看到如下图所示,即表示成功
在该页面点击鼠标右键-检查,切换到console面板,输入以下代码发起测试请求
fetch('/saveInfo', {
method: 'post',
body: JSON.stringify({
createDate: 1741318847,
type: 'test',
textValue: '这里是测试的内容'
}),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.text()).then(txt => console.log(txt))
控制台打印出如下内容,且数据库中出现新提交的测试数据即可
Info saved with ID: 1