我使用MERN堆栈创建了一个简单的CRUD应用程序。这个应用程序昨天工作正常,但今天当我对前端进行了一些更改,并开始运行应用程序,它无法正常工作并抛出与mongodb连接相关的错误。我也可以提供我的所有前端代码(但是在运行前端时它没有显示错误)。这是我在后端项目上执行npm start时遇到的错误:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server is running on Port: 4200
App starting error: MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/Users/afzaal/expressbackend/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:328:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (/Users/afzaal/expressbackend/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:274:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (/Users/afzaal/expressbackend/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:177:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1281:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
[nodemon] app crashed - waiting for file changes before starting...
这是我的app.js文件
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var port = 4200;
var cors = require('cors');
// Mongoose connection with mongodb
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/data')//what should I put for the URI?
.then(() => { // if all is ok we will be here
console.log('Start');
})
.catch(err => { // if error we will be here
console.error('App starting error:', err.stack);
process.exit(1);
});
// Required application specific custom router module
var itemRouter = require('./src/routes/itemRoutes');
// Use middlewares to set view engine and post json data to the server
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/items', itemRouter);
// Start the server
app.listen(port, function(){
console.log('Server is running on Port: ',port);
});
我确实安装了mongodb。我对mongodb很新,所以我不确定这是怎么回事。非常感谢任何帮助。