使用express创建服务器保存数据到mysql

发布于:2025-03-08 ⋅ 阅读:(105) ⋅ 点赞:(0)

创建数据库和表结构

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: 'root',    // 替换为你的数据库用户名
  password: '12345',// 替换为你的数据库密码
  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, type, textValue } = req.body;
  if (!createDate || !type || !textValue) {
    return res.status(400).send('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(201).send(`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

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到