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

创建数据库和表结构

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水晶心泉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值