Node.js API入门遇故障:本地3000端口无法访问+Mongoose未定义错误
Hey there, let's break down what's going wrong here and get your API up and running step by step!
First: Fix the Syntax Error (This is Why Nodemon is Crashing)
Looking at your code snippet, the immediate red flag is the misspelled functio... in your root route. That's a syntax error that's preventing Nodemon from starting your server at all—no wonder you can't access http://localhost:3000/! You need to correct that to function and add a proper callback body.
Second: You Forgot to Start the Server!
Even if you fix the syntax, your Express app won't listen on port 3000 unless you explicitly call app.listen(). That's a super common gotcha for new Node.js devs.
Third: Check MongoDB & Dependencies
- Make sure your local MongoDB service is running (type
mongodin a separate terminal, or use your system's service manager to start it). If MongoDB isn't running, Mongoose will fail to connect and might crash your server. - Double-check that you've installed all required dependencies: run
npm install express body-parser mongoose nodemon --saveto ensure nothing's missing.
Here's Your Corrected Full app.js Code
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); // Connect to MongoDB mongoose.connect('mongodb://localhost/arys'); var db = mongoose.connection; // Add connection status logs to debug DB issues db.on('error', console.error.bind(console, 'MongoDB connection error:')); db.once('open', function() { console.log('Successfully connected to MongoDB!'); }); // Set up body-parser middleware app.use(bodyParser.json()); // Import your Employee model Employee = require('./models/employee'); // Fixed root route with proper syntax app.get('/', function(req, res) { res.send('Your Node.js API is live! 🚀'); }); // Start the server on port 3000 (THIS WAS MISSING!) const PORT = 3000; app.listen(PORT, function() { console.log(`Server running at http://localhost:${PORT}/`); });
Step-by-Step Troubleshooting Checklist
- Fix the
functionspelling error in your root route. - Add the
app.listen()block to start the server on port 3000. - Verify MongoDB is running locally.
- Reinstall dependencies if needed.
- Restart Nodemon (it should auto-reload when you save changes, but you can run
npm startmanually if you've set up a start script inpackage.json).
Once you do all this, you should see a "Server running..." message in your terminal, and visiting http://localhost:3000/ will show your success message.
内容的提问来源于stack exchange,提问作者Jatinder Kumar

