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

复刻NYT Connections游戏时MySQL数据获取报错,Express能否解决?

问题:浏览器导入数据库操作脚本报错,使用Express能否解决?

我正在做一个复刻NYT Connections游戏的全栈学习项目,目前遇到了这样的问题:

  • 用Node.js写了database.js,它能成功连接本地数据库并获取数据,核心需求是按当前日期加载新单词到页面
  • 负责客户端交互(暗黑/亮色模式等功能)的script.js是唯一链接到HTML的脚本,但尝试从database.js导入initGameBoard函数时,浏览器持续报错
  • 我推测问题出在database.js里导入的mysql2和dotenv——浏览器没法直接运行Node.js专属的模块

相关代码如下:

// database.js
import mysql from 'mysql2';
import dotenv from 'dotenv';
dotenv.config();

const pool = mysql.createPool({
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE
}).promise();

export async function initGameBoard() {
    const [words] = await pool.query("SELECT * FROM Words WHERE set_id = (SELECT set_id FROM Sets WHERE publish_date = current_date())");
    let arr = [];
    for (let i = 0; i < words.length; i++) {arr[i] = words[i].word}
    return arr;
}
// script.js
import { initGameBoard } from './database.js'

// fetches data from DB to initialize first tile titles
document.addEventListener("DOMContentLoaded", () => {
    words = initGameBoard();
 });

是的,Express完全能解决你的问题。

核心原因很明确:浏览器是客户端运行环境,无法直接执行Node.js专属模块(比如mysql2、dotenv),这类数据库操作逻辑只能在Node.js服务端环境运行。

你需要做的是把数据库操作放到Express后端,客户端通过HTTP请求获取数据,具体步骤如下:

  1. 安装Express:
npm install express
  1. 创建后端服务器文件(比如server.js):
import express from 'express';
import { initGameBoard } from './database.js';
const app = express();
const port = 3000;

// 定义接口,返回当日单词数据
app.get('/api/daily-words', async (req, res) => {
  try {
    const words = await initGameBoard();
    res.json(words);
  } catch (err) {
    res.status(500).json({ error: '获取数据失败' });
  }
});

// 托管静态文件(你的HTML、CSS、客户端脚本)
app.use(express.static('public'));

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});
  1. 把你的HTML、script.js等静态文件放到项目根目录的public文件夹下

  2. 修改客户端script.js,通过fetch调用后端接口:

document.addEventListener("DOMContentLoaded", async () => {
  try {
    const response = await fetch('/api/daily-words');
    const words = await response.json();
    // 这里处理获取到的words,渲染到页面
    console.log(words);
  } catch (err) {
    console.error('加载单词失败:', err);
  }
});
  1. 启动服务器:
node server.js

之后访问http://localhost:3000就能正常获取并加载当日单词数据了。

这种方案把数据库操作隔离在服务端,客户端只负责请求数据,完全避开了浏览器不能运行Node.js模块的限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:05:15