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

Node.js API入门遇故障:本地3000端口无法访问+Mongoose未定义错误

Fixing Your Node.js API Connection & Nodemon Errors

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 mongod in 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 --save to 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

  1. Fix the function spelling error in your root route.
  2. Add the app.listen() block to start the server on port 3000.
  3. Verify MongoDB is running locally.
  4. Reinstall dependencies if needed.
  5. Restart Nodemon (it should auto-reload when you save changes, but you can run npm start manually if you've set up a start script in package.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:56:58