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

如何在浏览器端JavaScript应用中调用MariaDB数据?

解决方法:用极简后端接口实现数据展示

首先明确:你绝对不能在前端代码里直接连接MariaDB——这么做会直接把数据库的账号、密码、地址这些敏感信息暴露给所有访问页面的人,等于把数据库门户大开;而且MariaDB的Node.js驱动本身是为Node.js后端设计的,依赖浏览器没有的系统API,所以不管用Browserify还是ES模块都跑不起来。

给你一个最简化的实现方案,只用几行代码就能搞定:

步骤1:搭建极简后端接口(Node.js + Express)

  1. 新建一个文件夹,打开终端执行:
    npm init -y
    npm install express mariadb dotenv
    
  2. 在文件夹里创建server.js,代码如下:
    require('dotenv').config();
    const express = require('express');
    const mariadb = require('mariadb');
    const app = express();
    const port = 3000;
    
    // 创建数据库连接池
    const pool = mariadb.createPool({
      database: process.env.DATABASE,
      host: process.env.HOST,
      user: process.env.USER_TOKEN,
      password: process.env.PASSWORD,
    });
    
    // 定义获取数据的接口
    app.get('/api/data', async (req, res) => {
      let conn;
      try {
        conn = await pool.getConnection();
        // 替换成你实际的查询语句
        const rows = await conn.query('SELECT * FROM your_table_name');
        res.json(rows);
      } catch (err) {
        res.status(500).json({ error: err.message });
      } finally {
        if (conn) conn.release();
      }
    });
    
    // 开发阶段允许跨域请求(上线可调整配置)
    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      next();
    });
    
    app.listen(port, () => {
      console.log(`后端服务运行在 http://localhost:${port}`);
    });
    
  3. 把你的.env配置文件放到这个文件夹里,保持原有配置不变。

步骤2:修改前端代码

在你的index.html对应的app.js里,用fetch请求后端接口:

// app.js
window.addEventListener('load', async () => {
  try {
    const response = await fetch('http://localhost:3000/api/data');
    const data = await response.json();
    // 替换成你实际的页面渲染逻辑
    const container = document.getElementById('data-container');
    container.innerHTML = data.map(item => `<div>${JSON.stringify(item)}</div>`).join('');
  } catch (err) {
    console.error('获取数据失败:', err);
  }
});

在index.html中添加数据展示容器:

<div id="data-container"></div>

步骤3:运行测试

  1. 终端启动后端服务:node server.js
  2. 打开你的index.html页面,就能看到从数据库获取并展示的数据了。

这个方案看似多了一步后端,但代码量极少,完全规避了安全风险,也是前端获取数据库数据的标准做法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:48:17