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

使用Node.js和Express连接数据库时GET请求无响应求助

Troubleshooting Your Express-MySQL /users Endpoint Issue

Hey there! Let's walk through why your /users GET request isn't getting a response and fix it up step by step. I spot a couple of key missing pieces in your code that are almost certainly causing this problem.

1. You're Not Actually Connecting to the Database

Your code creates a database connection object, but it never initiates the connection to MySQL. If the app can't reach the database, the query will hang indefinitely, leaving your request waiting for a response with no end in sight.

Add this right after creating the db object to handle the connection and log any issues:

db.connect((err) => {
  if (err) {
    console.error('Failed to connect to MySQL:', err);
    return;
  }
  console.log('Successfully connected to the userdb database!');
});

2. No Error Handling for the Database Query

Right now, if your SELECT * FROM users query fails (e.g., the users table doesn't exist, you have wrong permissions, or a typo in the query), your code never sends a response back to the client. The request will just hang until it times out.

Update your /users endpoint to handle errors explicitly so you get feedback instead of silence:

app.get("/users", (req, res) => {
    db.query("SELECT * FROM users", (err, result) => {
        // Handle query errors first
        if (err) {
          console.error('Query failed:', err);
          return res.status(500).json({ error: 'Failed to fetch users', details: err.message });
        }
        // Send the result if everything works
        res.json(result);
    });
});

3. Double-Check Your Database Setup

Before testing again, confirm these details:

  • The userdb database exists in your local MySQL instance
  • The users table is present inside userdb
  • Your root MySQL user has the correct password (you have an empty string here—make sure that matches your local setup)
  • MySQL is running on the default port 3306; if you changed it, add a port property to your connection config (e.g., port: "3307")

Full Modified Code

Here's the complete code with all fixes applied:

const express = require('express');
const app = express();
const mysql = require('mysql');

const db = mysql.createConnection({
    user: "root",
    host:"localhost",
    password:"", // Confirm this matches your MySQL root password
    database:"userdb",
    // Uncomment and update if using a non-default port:
    // port: "3307"
});

// Connect to database and log status
db.connect((err) => {
  if (err) {
    console.error('Database connection error:', err);
    return;
  }
  console.log('Connected to MySQL database successfully!');
});

app.use(express.json());

app.get("/users", (req, res) => {
    db.query("SELECT * FROM users", (err, result) => {
        if (err) {
          console.error('Fetch users query failed:', err);
          return res.status(500).json({ error: 'Could not retrieve users', details: err.message });
        }
        res.json(result);
    });
});

app.listen(3001, () => console.log('Listening on port 3001...'));

How to Test

  1. Start your app and check the console: you should see "Connected to MySQL database successfully!" if the connection works.
  2. Send a GET request to http://localhost:3001/users using Postman, curl, or your browser.
  3. If there's an error, you'll get a clear JSON response with details, and the console will log the issue to help you debug further.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 10:40:39