如何在React+NodeJS环境下向MySQL数据库发送对象数组
React+NodeJS+MySQL批量插入课程时段实现方案
我是NodeJS和MySQL的新手,正在开发一个带后端的React周历预约项目,学生可在此预约课程。目前正在制作管理员面板,供教师创建包含选定可用时段的周历,所有选定时段存储在React state中,格式如下:
[ {year: '2023', user_uuid: 2, dayId: 2, hourId: 0, hour: '7:00'}, {year: '2023', user_uuid: 2, dayId: 5, hourId: 0, hour: '7:00'}, {year: '2023', user_uuid: 2, dayId: 4, hourId: 0, hour: '7:00'}, {year: '2023', user_uuid: 2, dayId: 4, hourId: 1, hour: '7:45'}, // ...更多时段数据 ]
后端NodeJS实现代码(已优化)
const express = require("express"); const mysql = require("mysql"); const cors = require("cors") const app = express(); const db = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "meetapp" }) app.use(express.json()) app.use(cors()) app.get("/", (req, res) =>{ res.json("hello this is the backend") }) app.post("/terms", (req, res) => { const q = "INSERT INTO terms (year, user_uuid, dayId, hourId, hour) VALUES ?" const bulkValues = req.body.map((values) => [ values.year, values.user_uuid, values.dayId, values.hourId, values.hour, ]); console.log('bulk is', bulkValues) db.query(q, [bulkValues], (err, data) => { if(err) return res.json(err) return res.json(data) }) }) app.listen(8801, () => { console.log(`Backend works! Listening on 8801`); });
前端React POST请求函数
const saveWeek = async e => { e.preventDefault() try { await axios.post("http://localhost:8801/terms", sortedTerms) } catch (err) { console.log(err) } }
其中sortedTerms是存储时段数据的React state。
验证结果
触发saveWeek后,数据成功发送至后端,后端控制台输出转换后的批量插入数据格式:
bulk is [ [ '2023', 2, 0, 0, '7:00' ], [ '2023', 2, 1, 0, '7:00' ], [ '2023', 2, 2, 0, '7:00' ], [ '2023', 2, 3, 0, '7:00' ], [ '2023', 2, 3, 1, '7:45' ], [ '2023', 2, 3, 2, '8:30' ], [ '2023', 2, 6, 20, '22:00' ], [ '2023', 2, 5, 20, '22:00' ] ]
经优化后代码可正常将所有时段数据批量保存至MySQL数据库,希望能帮助其他开发者。
内容的提问来源于stack exchange,提问作者MarcinB
相关产品推荐
相关产品推荐

