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

如何使用Node.js将HTML文档与SQL数据库连接并关联其他JS?

嘿,我来帮你把这个事儿理清楚——首先得明确一个核心点:你没法直接在HTML里引入Node.js,因为Node.js是运行在服务器端的环境,而HTML是在浏览器里跑的前端代码。两者得通过「后端API接口」来通信,下面是一步步的落地方案,我用MySQL举例子,换成PostgreSQL、SQL Server这类SQL数据库思路也差不多:

第一步:初始化Node.js后端项目
  • 先建个项目文件夹,打开终端跑命令初始化项目:
    npm init -y
  • 安装需要的依赖:Express(快速搭建服务器)、mysql2(连接MySQL的现代工具包)、cors(解决开发阶段的跨域问题)
    npm install express mysql2 cors
第二步:连接你的SQL数据库

新建一个db.js文件,专门处理数据库连接:

const mysql = require('mysql2');

// 替换成你自己的数据库配置
const db = mysql.createConnection({
  host: 'localhost', // 本地数据库一般是localhost
  user: 'your_db_username', // 比如root
  password: 'your_db_password', // 你的数据库密码
  database: 'your_target_db' // 要连接的数据库名称
});

// 测试连接是否成功
db.connect((err) => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  console.log('成功连接到SQL数据库 🎉');
});

module.exports = db;
第三步:写后端API接口处理数据记录

新建server.js文件,搭建服务器并编写接收前端数据的接口:

const express = require('express');
const cors = require('cors');
const db = require('./db');

const app = express();
const port = 3000; // 后端服务的运行端口

// 中间件配置:允许跨域请求、解析JSON格式的请求体
app.use(cors());
app.use(express.json());

// 编写一个POST接口,用来接收前端传来的数据并存入数据库
app.post('/api/save-record', (req, res) => {
  // 从请求体中提取前端发送的数据(这里假设你要存name和phone两个字段)
  const { name, phone } = req.body;

  // SQL插入语句,用?做占位符防止SQL注入
  const insertSql = 'INSERT INTO your_table_name (name, phone) VALUES (?, ?)';
  const values = [name, phone];

  db.query(insertSql, values, (err, result) => {
    if (err) {
      console.error('数据插入失败:', err);
      return res.status(500).json({ success: false, msg: '数据存储失败' });
    }
    res.json({ success: true, msg: '数据存储成功', recordId: result.insertId });
  });
});

// 启动服务器
app.listen(port, () => {
  console.log(`后端服务已启动,地址:http://localhost:${port}`);
});
第四步:前端HTML通过JS调用API提交数据

写一个简单的index.html文件,用原生JS的fetch方法调用后端接口:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>数据提交示例</title>
</head>
<body>
  <h2>提交数据到数据库</h2>
  <form id="recordForm">
    <div>
      <label>姓名:</label>
      <input type="text" id="nameInput" required>
    </div>
    <div style="margin: 10px 0;">
      <label>电话:</label>
      <input type="tel" id="phoneInput" required>
    </div>
    <button type="submit">提交</button>
  </form>

  <script>
    const form = document.getElementById('recordForm');

    form.addEventListener('submit', async (e) => {
      e.preventDefault(); // 阻止表单默认跳转行为

      const name = document.getElementById('nameInput').value;
      const phone = document.getElementById('phoneInput').value;

      try {
        // 调用后端API
        const response = await fetch('http://localhost:3000/api/save-record', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ name, phone })
        });

        const result = await response.json();
        if (result.success) {
          alert('数据提交成功!记录ID:' + result.recordId);
          form.reset(); // 重置表单
        } else {
          alert('提交失败:' + result.msg);
        }
      } catch (error) {
        console.error('请求出错:', error);
        alert('网络请求失败,请检查后端服务是否启动');
      }
    });
  </script>
</body>
</html>
第五步:测试运行
  1. 确保你的SQL数据库已经启动,并且提前创建好对应的表(比如your_table_name,要有name和phone字段)
  2. 启动后端服务:在终端跑node server.js,看到数据库连接成功和服务启动的提示就没问题
  3. 直接在浏览器打开index.html,填写表单提交,去数据库里查看数据是否已经存入
额外注意事项
  • 所有配置项(数据库用户名、密码、表名等)一定要换成你自己的实际信息
  • 生产环境不要把数据库密码硬编码在代码里,用环境变量(比如process.env.DB_PASSWORD)来管理
  • 开发阶段可以用nodemon自动重启后端服务:npm install -g nodemon,然后用nodemon server.js启动
  • 如果前端和后端最终部署在同一个域名下,可以去掉cors中间件,避免不必要的配置

内容的提问来源于stack exchange,提问作者theratcoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:35:06