如何将前端JavaScript变量传递到Node.js服务端并存入MySQL数据库
调整方案
1. 前端代码修改
调整两个核心点:
- 原代码仅获取了输入框DOM元素,需要补充获取
value属性拿到实际输入内容 - 新增
fetch请求将数据以POST方式传递到后端接口
修改后完整前端代码:
<!DOCTYPE html> <html> <body> <h2>HTML Forms</h2> <form> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname" value="John"><br> </form> <button onclick="hello()">Click me</button> </body> <script> function hello () { // 取输入框实际内容 const passedVariable = document.getElementById("fname").value; // 发送请求到后端 fetch('/api/save-name', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fname: passedVariable }) }).then(res => res.json()) .then(data => { if(data.success) alert('提交成功') }) .catch(err => console.error('请求失败:', err)) } </script> </html>
2. 后端代码修改
调整三个核心点:
- 新增
express.json()中间件,用于解析前端传递的JSON格式请求体 - 移除服务启动时自动执行的SQL插入逻辑,将插入逻辑封装到独立的POST接口中
- 使用参数化查询执行SQL操作,避免SQL注入风险
修改后完整后端代码:
const express = require("express"); const app = express(); const mysql = require('mysql'); // 解析JSON请求体中间件 app.use(express.json()); // 静态文件服务 app.use(express.static(__dirname)); // 数据库配置替换为自己实际的配置 const con = mysql.createConnection({ host: "localhost", user: "root", password: "你的MySQL密码", database: "dbname" }); con.connect(function(err) { if (err) throw err; console.log("数据库连接成功!"); }); // 首页路由 app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); }); // 接收前端数据的接口 app.post('/api/save-name', (req, res) => { const inputContent = req.body.fname; // 参数化查询 const sql = "INSERT INTO files(email) VALUES (?)"; con.query(sql, [inputContent], function (err, result) { if (err) { console.error('插入失败:', err); return res.json({success: false, msg: '插入失败'}); } console.log("1条记录插入成功"); res.json({success: true, msg: '提交成功'}); }); }); app.listen(3000, () => { console.log("服务已启动,监听端口3000"); });
前置准备与测试
- 安装项目依赖:执行
npm install express mysql - 确保本地MySQL服务已启动,对应数据库
dbname、files表已存在,email字段为可存储字符串的类型 - 启动Node服务后访问
http://localhost:3000,输入内容点击按钮即可提交数据存入数据库
内容的提问来源于stack exchange,提问作者Mystery Man
相关产品推荐
相关产品推荐

