Node.js路由故障排查:启动应用后显示无程序运行的问题
Hey there! Let's break down the common issues that might be causing this error, using your code as a reference. I'll walk you through each check step by step:
1. Your app isn't actually starting a server (the most likely culprit!)
Looking at your app.js, you've set up all the Express middleware and routes, but you never tell the app to listen for incoming requests. Express requires a call to app.listen() to start the server.
Add this code to the very end of your app.js:
// Start the server const PORT = process.env.PORT || 3000; // Cloud9 requires binding to 0.0.0.0 for external access app.listen(PORT, '0.0.0.0', () => { console.log(`Server is running and listening on port ${PORT}`); });
Cloud9 uses environment variables for the port, so using process.env.PORT ensures you match the platform's requirements. The 0.0.0.0 host makes the server accessible via your Cloud9 URL.
2. You're mounting your router twice (causing route conflicts)
In app.js, you have:
app.use('/', Router); app.use('/quiz',Router);
This duplicates your router's routes under both / and /quiz. For example:
- The router's
/path will now respond to bothhttp://your-url/ANDhttp://your-url/quiz/ - The router's
/quizpath will becomehttp://your-url/quiz/quiz(which is probably not what you want)
Fix this by removing one of the mounts. Keep just:
app.use('/', Router);
Now your routes will work as expected:
GET /→ renders your index viewGET /quiz→ callsquizController.doGetQuiz
3. Verify all dependencies are installed
Make sure every package you're require()-ing is installed in your project. Run this command in your terminal:
npm install express ejs morgan cookie-parser http-errors
If any package is missing, your app will throw an error on startup—check your terminal for messages like Cannot find module 'xxx' to spot this.
4. Check if your view files exist
Your router tries to render index with res.render("index")—make sure there's an index.ejs file in your views folder (the one you set with app.set('views', path.join(__dirname, 'views'))). If the file is missing, the server will throw an error when you try to access the root path.
5. Look at your terminal output for errors
When you run node app.js, your terminal will print any startup errors. These are gold for troubleshooting! Common issues here include:
- Missing modules
- File path errors (e.g., wrong path to views or controllers)
- Syntax errors in your code
Final Testing Steps
- Fix the
app.listen()issue first—this is the most critical fix - Remove the duplicate router mount
- Run
npm installto ensure all dependencies are present - Start your app again with
node app.js(you don't need to pass the URL as an argument—your app will use the correct port/host from the code above) - Check the terminal for the "Server is running..." message, then visit your Cloud9 URL again
内容的提问来源于stack exchange,提问作者Heisenberg

