Node.js部署Heroku时遇Cannot GET /times及/db错误求助
Hey there! Let's walk through why you're hitting those Cannot GET errors and how to fix them—since you're new to Node.js, I'll keep this simple and step-by-step.
1. You're Missing Route Definitions in Your App
First off, the Cannot GET error usually means your Express app doesn't have a GET route defined for /times or /db.
Double-check your main server file (probably app.js or server.js) to make sure you have code that looks like this:
// Example /times route app.get('/times', (req, res) => { let result = ''; const times = process.env.TIMES || 5; for (i=0; i < times; i++) { result += i + ' '; } res.send(result); }); // Example /db route (connected to your database) app.get('/db', async (req, res) => { try { const client = await pool.connect(); const result = await client.query('SELECT * FROM test_table'); res.send(result.rows); client.release(); } catch (err) { console.error(err); res.send("Error " + err); } });
If these routes are missing entirely, that's definitely the issue—add them from the tutorial and redeploy.
2. Your Latest Code Changes Aren't on Heroku
Heroku only runs the code you've pushed to its Git repository. If you added the routes locally but didn't push them up, Heroku has no idea they exist!
Run these commands in your terminal to push your local changes:
git add . git commit -m "Add /times and /db routes" git push heroku main
Wait for the deployment to finish, then try heroku open times again.
3. You're Hardcoding the Server Port
Heroku assigns a dynamic port to your app, so you can't use a fixed port like 3000 in your code. Make sure your server listens on the port provided by Heroku:
const port = process.env.PORT || 3000; // Use Heroku's port, or 3000 for local testing app.listen(port, () => { console.log(`Server running on port ${port}`); });
If you're hardcoding 3000, Heroku's server won't be able to route requests to your app, leading to those 404 errors.
4. Check Heroku Logs for Hidden Clues
If the above steps don't fix it, let's dig into the logs—they'll tell you exactly what's going wrong. Run this command in your terminal to see real-time logs:
heroku logs --tail
Now, try opening /times or /db again, and watch the logs. You might see:
- A
404entry confirming the route doesn't exist (go back to step 1) - Database connection errors (double-check your config vars for the database URL)
- Server startup errors (like missing dependencies or syntax mistakes)
5. Verify Your Config Vars Are Set Correctly
For the /db route specifically, make sure your database config var (like DATABASE_URL) is properly set in Heroku. You can check this by running:
heroku config
If your database URL is missing or incorrect, your /db route will fail—but if the route itself isn't defined, you'll still get the Cannot GET /db error first.
内容的提问来源于stack exchange,提问作者low kim




