You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将前端JavaScript变量传递到Node.js服务端并存入MySQL数据库

调整方案

1. 前端代码修改

调整两个核心点:

  1. 原代码仅获取了输入框DOM元素,需要补充获取value属性拿到实际输入内容
  2. 新增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. 后端代码修改

调整三个核心点:

  1. 新增express.json()中间件,用于解析前端传递的JSON格式请求体
  2. 移除服务启动时自动执行的SQL插入逻辑,将插入逻辑封装到独立的POST接口中
  3. 使用参数化查询执行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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:45:03