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

请求访问test数据库时加载停滞,数据库连接问题求助

问题排查与修复方案

核心问题分析

你的代码存在两个关键问题,直接导致请求停滞和数据库访问异常:

  • 未主动建立数据库连接:使用mysql.createConnection()创建连接对象后,没有调用db.connect()触发实际连接流程,数据库操作一直处于等待连接建立的状态,导致请求停滞。
  • 接口未返回响应:/books接口中,查询成功后仅return data,没有通过res.json(data)将结果返回给客户端,请求会一直挂起等待响应。

另外,配置database: "books"时返回“database is unknown”,说明你的MySQL中确实不存在books数据库;使用test时无该错误,说明test数据库是存在的,只是连接未建立导致请求停滞。

修复后的代码

// To import these packages remember to add "type":"module" to package Json
import express from "express";
import mysql from "mysql";

const app = express();

const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "keks000207",
  database: "test",
});

// 建立数据库连接并处理连接错误
db.connect((err) => {
  if (err) {
    console.error("数据库连接失败:", err);
    return;
  }
  console.log("成功连接到MySQL数据库");
});

// This is an API request with an Express server
app.get("/", (req, res) => {
  res.json("Hello this is the backend");
});

app.get("/books", (req, res) => {
  const q = "SELECT * FROM books";
  db.query(q, (err, data) => {
    if (err) return res.json(err);
    // 将查询结果返回给客户端
    return res.json(data);
  });
});

app.listen(8800, () => {
  console.log("Connected to backend!");
});

额外建议

  • 确认test数据库中存在books表,否则查询会返回“table not found”错误
  • 生产环境建议使用连接池(mysql.createPool())替代单连接,提升性能和稳定性
  • 可添加连接超时、错误重试逻辑,增强代码健壮性

内容的提问来源于stack exchange,提问作者keanu.b

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:10:49