通过邮递员测试时无法通过猫鼬连接到MongoDB

时间:2019-12-01 08:49:16

标签: node.js mongodb express mongoose nodemon

我无法通过邮递员连接到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

还-我正在阅读一个多元指导教程,可能是这些包是旧的,我正在查看package.json-但我完全迷失了

api /用户

    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 /交易



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

3 个答案:

答案 0 :(得分:0)

该错误可能是因为您尝试访问的路由未由您定义。请检查您是否在API中定义了此POST路由。

http://localhost:8080/api/user/?ObjectId=5a777f0a75f64a1698221d98.

如果正确定义了路由,但是在执行路由中定义的代码时,由于未处理的错误,服务器也会崩溃,也会发生此错误。如有可能,请在此处粘贴api.js中的代码。

答案 1 :(得分:0)

尝试

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!后,您的服务器似乎也没有监听

答案 2 :(得分:0)

app.js-10

app.use(bodyParser.json)应该是app.use(bodyParser.json())