使用Node.js和Express连接数据库时GET请求无响应求助
/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
userdbdatabase exists in your local MySQL instance - The
userstable is present insideuserdb - Your
rootMySQL 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 aportproperty 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
- Start your app and check the console: you should see "Connected to MySQL database successfully!" if the connection works.
- Send a GET request to
http://localhost:3001/usersusing Postman, curl, or your browser. - 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

