Vue.js(组合式API)项目连接MySQL数据库及require报错问题咨询
解决Vue项目中无法使用mysql2连接MySQL的问题
核心问题说明
Vue是前端框架,代码运行在浏览器环境中,不能直接在前端代码里连接MySQL数据库:
- 浏览器不支持Node.js的
require语法(这就是你遇到"require is not defined"的原因) - 直接在前端暴露数据库连接信息会导致严重的安全风险(比如账号密码泄露)
正确的实现方案
你需要通过后端服务作为中间层来处理数据库请求,步骤如下:
- 搭建一个简单的后端服务(比如用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}`); });
- 后端里使用
- 在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>
- 示例Vue组合式API代码:
关于package.json的type字段
你的Vue项目默认是ES模块环境(支持import/export),没有type字段的话,Node.js会默认按CommonJS处理,但这和你前端的问题无关——因为前端代码根本不应该使用mysql2模块。
内容的提问来源于stack exchange,提问作者Atomic
相关产品推荐
相关产品推荐

