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

能否通过JavaScript函数执行SQL查询?前端触发数据库查询实现求助

问题分析与解决方案

你当前的实现存在核心问题:直接在前端JavaScript中使用Node.js的mysql模块完全不可行——浏览器环境不支持Node.js的require语法,更关键的是这种写法会直接暴露数据库账号密码,存在严重的安全风险。

正确的实现逻辑是:

  • 后端用Node.js编写API接口,负责连接MySQL数据库并执行查询
  • 前端点击按钮后,通过网络请求调用后端接口,获取数据后渲染到页面

1. 后端API实现(Node.js)

先创建后端服务文件server.js,用Express快速搭建接口(需先安装依赖:npm install express mysql):

const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3000;

// 数据库连接配置
const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: 'app_db'
});

// 连接数据库
con.connect(err => {
    if (err) {
        console.error('数据库连接失败:', err);
        return;
    }
    console.log('已成功连接到数据库');
});

// 跨域配置,允许前端页面访问
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

// 定义查询武器数据的接口
app.get('/api/weapons', (req, res) => {
    con.query("SELECT * FROM weapons", (err, result) => {
        if (err) {
            console.error('查询失败:', err);
            res.status(500).json({ error: '查询数据失败' });
            return;
        }
        res.json(result);
    });
});

// 启动服务
app.listen(port, () => {
    console.log(`后端服务运行在 http://localhost:${port}`);
});

2. 前端代码修改

index.html

移除后端数据库连接文件的引用,添加数据展示容器:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/styles.css">
    <script rel="text/javascript" src="js/index.js"></script>
    <title>武器数据查询</title>
</head>
<body>
    <h1>武器数据查询</h1>
    <div class="container">
        <button onclick="get_weapons()">获取武器数据</button>
        <!-- 数据展示容器 -->
        <div id="weapons-table-container" class="table-container"></div>
    </div>
</body>
</html>

js/index.js

编写请求接口与渲染数据的函数:

async function get_weapons() {
    try {
        const response = await fetch('http://localhost:3000/api/weapons');
        if (!response.ok) {
            throw new Error('请求失败');
        }
        const weapons = await response.json();
        renderWeaponsTable(weapons);
    } catch (error) {
        console.error('获取数据出错:', error);
        alert('获取数据失败,请检查后端服务是否运行');
    }
}

// 将数据渲染为表格
function renderWeaponsTable(weapons) {
    const container = document.getElementById('weapons-table-container');
    if (weapons.length === 0) {
        container.innerHTML = '<p>暂无武器数据</p>';
        return;
    }

    // 生成表格头部
    const headers = Object.keys(weapons[0]);
    let tableHTML = '<table class="weapons-table"><thead><tr>';
    headers.forEach(header => {
        tableHTML += `<th>${header}</th>`;
    });
    tableHTML += '</tr></thead><tbody>';

    // 生成表格内容
    weapons.forEach(weapon => {
        tableHTML += '<tr>';
        headers.forEach(header => {
            tableHTML += `<td>${weapon[header] || ''}</td>`;
        });
        tableHTML += '</tr>';
    });

    tableHTML += '</tbody></table>';
    container.innerHTML = tableHTML;
}

3. 样式文件(css/styles.css)

添加基础美化样式:

.container {
    max-width: 800px;
    margin: 20px auto;
    padding: 0 20px;
}

button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: #0056b3;
}

.table-container {
    margin-top: 20px;
}

.weapons-table {
    width: 100%;
    border-collapse: collapse;
}

.weapons-table th, .weapons-table td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

.weapons-table th {
    background-color: #f2f2f2;
    font-weight: bold;
}

.weapons-table tr:hover {
    background-color: #f5f5f5;
}

运行步骤

  1. 启动WAMP的MySQL服务,确保数据库app_db和表weapons存在
  2. 运行后端服务:node server.js
  3. 打开前端index.html页面,点击按钮即可获取并展示数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:03:35