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

Vue.js(组合式API)项目连接MySQL数据库及require报错问题咨询

解决Vue项目中无法使用mysql2连接MySQL的问题

核心问题说明

Vue是前端框架,代码运行在浏览器环境中,不能直接在前端代码里连接MySQL数据库:

  • 浏览器不支持Node.js的require语法(这就是你遇到"require is not defined"的原因)
  • 直接在前端暴露数据库连接信息会导致严重的安全风险(比如账号密码泄露)

正确的实现方案

你需要通过后端服务作为中间层来处理数据库请求,步骤如下:

  1. 搭建一个简单的后端服务(比如用Express + Node.js)
    • 后端里使用mysql2连接MySQL,编写接口提供数据
    • 示例后端代码:
      const express = require('express');
      const mysql = require('mysql2');
      const app = express();
      const port = 3001;
      
      // 创建数据库连接
      const connection = mysql.createConnection({
        host: '你的数据库地址',
        user: '数据库用户名',
        password: '数据库密码',
        database: '数据库名'
      });
      
      // 测试连接
      connection.connect((err) => {
        if (err) throw err;
        console.log('数据库连接成功!');
      });
      
      // 编写接口返回数据
      app.get('/api/data', (req, res) => {
        connection.query('SELECT * FROM 你的表名', (err, results) => {
          if (err) throw err;
          res.json(results);
        });
      });
      
      app.listen(port, () => {
        console.log(`后端服务运行在 http://localhost:${port}`);
      });
      
  2. 在Vue项目中通过fetch或axios调用后端接口获取数据
    • 示例Vue组合式API代码:
      <script setup>
      import { ref, onMounted } from 'vue';
      const dataList = ref([]);
      
      onMounted(async () => {
        try {
          const response = await fetch('http://localhost:3001/api/data');
          dataList.value = await response.json();
        } catch (error) {
          console.error('获取数据失败:', error);
        }
      });
      </script>
      

关于package.json的type字段

你的Vue项目默认是ES模块环境(支持import/export),没有type字段的话,Node.js会默认按CommonJS处理,但这和你前端的问题无关——因为前端代码根本不应该使用mysql2模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:52:52