通过邮递员测试时无法通过猫鼬连接到 MongoDB
Can't connect to MongoDB via mongoose when testing through postman
我无法通过 Postman 连接到 mongoDB 来发出任何请求...
我在我的控制台中得到这个:
[nodemon] starting `node app.js`
API Server Listening on port 8080!
这是我的 app.js:
```
const express = require('express')
const app = express()
const api = require('./api')
const morgan = require('morgan') // logger
const bodyParser = require('body-parser')
const cors = require('cors')
app.set('port', (process.env.PORT || 8080))
app.use(bodyParser.json)
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(cors())
app.use('/api', api)
app.use(express.static('static'))
app.use(morgan('dev'))
app.use(function (req, res) {
const err = new Error('Not Found')
err.status = 404
res.json(err)
})
// Add MongoDB connection and mongoose
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/globomantics', {
useNewUrlParser: true, //deprecated url parser
useUnifiedTopology: true
})
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function () {
app.listen(app.get('port'), function () {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
})
```
我从邮递员那里得到的是:
There was an error connecting to http://localhost:8080/api/user/?ObjectId=5a777f0a75f64a1698221d98.
这是 api 文件夹结构:
API>
routes>
User>
Transaction>
index.js
另外 - 我正在学习一个 pluralsight 教程,可能是我正在查看的包是旧的 package.json - 但我完全迷路了
api/user
const User = require('../../models/user')
module.exports = function (router) {
router.get('/user/:id', function (req, res) {
User.findById(req.params.id).exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding user',
error: err
}))
})
router.get('/user/email/:email', function (req, res) {
User.find({ 'email': req.params.email }).exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding user',
error: err
}))
})
router.post('/user', function (req, res) {
let user = new User(req.body)
user.save(function (err, user) {
if (err) return console.log(err)
res.status(200).json(user)
})
})
router.put('/user/:id', function (req, res) {
console.log(req.body)
let qry = { _id: req.params.id }
let doc = {
// first: req.body.firstName,
// last: req.body.lastName,
// email: req.body.email,
// password: req.body.password,
isActive: req.body.isActive
}
console.log(doc)
User.update(qry, doc, function (err, respRaw) {
if (err) return console.log(err)
res.status(200).json(respRaw)
})
})
}
API/transaction
const Transaction = require('../../models/transaction')
const mongoose = require('mongoose')
module.exports = function (router) {
// Get transactions for given year and month, by userId...
router.get('/transaction/:year/:month', function (req, res) {
const userId = req.get('userId')
const month = req.params.month - 1 // JS months are zero-based
const year = req.params.year
const startDt = new Date(Date.UTC(year, month, 1, 0, 0, 0))
const endDt = new Date(Date.UTC(year, month + 1, 1, 0, 0, 0))
const qry = {
userId: userId,
transactionDate: {
$gte: startDt,
$lt: endDt
}
}
Transaction.find(qry)
.sort({ 'transactionDate': 1 })
.exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding transactions for user',
error: err
}))
})
// Get transactions running balance for a specific user...
router.get('/transaction/balance/:year/:month', function (req, res) {
const userId = req.get('userId')
const month = req.params.month - 1 // JS months are zero-based
const year = req.params.year
const endDt = new Date(Date.UTC(year, month, 1))
const pipeline = [
{
$match: {
userId: mongoose.Types.ObjectId(userId),
}
},
{
$match: {
transactionDate: { $lt: endDt }
}
},
{
$group: {
_id: null,
charges: { $sum: '$charge' },
deposits: { $sum: '$deposit' }
}
}
]
Transaction.aggregate(pipeline).exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding transactions for user',
error: err
}))
})
// Create new transaction document
router.post('/transaction', function (req, res) {
let transaction = new Transaction(req.body)
transaction.save(function (err, transaction) {
if (err) return console.log(err)
res.status(200).json(transaction)
})
})
}
API/indexjs
const express = require('express')
const router = express.Router()
require('./routes/transaction')(router)
require('./routes/user')(router)
module.exports = router
错误可能是因为您尝试访问的路由不是您定义的。请检查您是否已在 API 中定义此 POST
路由。
http://localhost:8080/api/user/?ObjectId=5a777f0a75f64a1698221d98.
如果您的路由定义正确,但当您执行路由中定义的代码时,您的服务器由于未处理的错误而崩溃,也会发生此错误。如果可能,请在此处粘贴 api.js
中的代码。
尝试
db.once('open', function () {
console.log('connection Opened ')
})
app.listen(app.get('port'), function () {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
而不是
db.once('open', function () {
app.listen(app.get('port'), function () {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
})
因为您的服务器似乎没有在监听,即使在登录后也是如此 API Server Listening on port 8080!
app.js - 10
app.use(bodyParser.json) 应该是 app.use(bodyParser.json())
我无法通过 Postman 连接到 mongoDB 来发出任何请求...
我在我的控制台中得到这个:
[nodemon] starting `node app.js`
API Server Listening on port 8080!
这是我的 app.js:
```
const express = require('express')
const app = express()
const api = require('./api')
const morgan = require('morgan') // logger
const bodyParser = require('body-parser')
const cors = require('cors')
app.set('port', (process.env.PORT || 8080))
app.use(bodyParser.json)
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(cors())
app.use('/api', api)
app.use(express.static('static'))
app.use(morgan('dev'))
app.use(function (req, res) {
const err = new Error('Not Found')
err.status = 404
res.json(err)
})
// Add MongoDB connection and mongoose
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/globomantics', {
useNewUrlParser: true, //deprecated url parser
useUnifiedTopology: true
})
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function () {
app.listen(app.get('port'), function () {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
})
```
我从邮递员那里得到的是:
There was an error connecting to http://localhost:8080/api/user/?ObjectId=5a777f0a75f64a1698221d98.
这是 api 文件夹结构:
API>
routes>
User>
Transaction>
index.js
另外 - 我正在学习一个 pluralsight 教程,可能是我正在查看的包是旧的 package.json - 但我完全迷路了
api/user
const User = require('../../models/user')
module.exports = function (router) {
router.get('/user/:id', function (req, res) {
User.findById(req.params.id).exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding user',
error: err
}))
})
router.get('/user/email/:email', function (req, res) {
User.find({ 'email': req.params.email }).exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding user',
error: err
}))
})
router.post('/user', function (req, res) {
let user = new User(req.body)
user.save(function (err, user) {
if (err) return console.log(err)
res.status(200).json(user)
})
})
router.put('/user/:id', function (req, res) {
console.log(req.body)
let qry = { _id: req.params.id }
let doc = {
// first: req.body.firstName,
// last: req.body.lastName,
// email: req.body.email,
// password: req.body.password,
isActive: req.body.isActive
}
console.log(doc)
User.update(qry, doc, function (err, respRaw) {
if (err) return console.log(err)
res.status(200).json(respRaw)
})
})
}
API/transaction
const Transaction = require('../../models/transaction')
const mongoose = require('mongoose')
module.exports = function (router) {
// Get transactions for given year and month, by userId...
router.get('/transaction/:year/:month', function (req, res) {
const userId = req.get('userId')
const month = req.params.month - 1 // JS months are zero-based
const year = req.params.year
const startDt = new Date(Date.UTC(year, month, 1, 0, 0, 0))
const endDt = new Date(Date.UTC(year, month + 1, 1, 0, 0, 0))
const qry = {
userId: userId,
transactionDate: {
$gte: startDt,
$lt: endDt
}
}
Transaction.find(qry)
.sort({ 'transactionDate': 1 })
.exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding transactions for user',
error: err
}))
})
// Get transactions running balance for a specific user...
router.get('/transaction/balance/:year/:month', function (req, res) {
const userId = req.get('userId')
const month = req.params.month - 1 // JS months are zero-based
const year = req.params.year
const endDt = new Date(Date.UTC(year, month, 1))
const pipeline = [
{
$match: {
userId: mongoose.Types.ObjectId(userId),
}
},
{
$match: {
transactionDate: { $lt: endDt }
}
},
{
$group: {
_id: null,
charges: { $sum: '$charge' },
deposits: { $sum: '$deposit' }
}
}
]
Transaction.aggregate(pipeline).exec()
.then(docs => res.status(200)
.json(docs))
.catch(err => res.status(500)
.json({
message: 'Error finding transactions for user',
error: err
}))
})
// Create new transaction document
router.post('/transaction', function (req, res) {
let transaction = new Transaction(req.body)
transaction.save(function (err, transaction) {
if (err) return console.log(err)
res.status(200).json(transaction)
})
})
}
API/indexjs
const express = require('express')
const router = express.Router()
require('./routes/transaction')(router)
require('./routes/user')(router)
module.exports = router
错误可能是因为您尝试访问的路由不是您定义的。请检查您是否已在 API 中定义此 POST
路由。
http://localhost:8080/api/user/?ObjectId=5a777f0a75f64a1698221d98.
如果您的路由定义正确,但当您执行路由中定义的代码时,您的服务器由于未处理的错误而崩溃,也会发生此错误。如果可能,请在此处粘贴 api.js
中的代码。
尝试
db.once('open', function () {
console.log('connection Opened ')
})
app.listen(app.get('port'), function () {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
而不是
db.once('open', function () {
app.listen(app.get('port'), function () {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
})
因为您的服务器似乎没有在监听,即使在登录后也是如此 API Server Listening on port 8080!
app.js - 10
app.use(bodyParser.json) 应该是 app.use(bodyParser.json())