skip to Main Content

I am using Node JS and Express, whenever I run the GET request with this link http://localhost:3500/balanceDue on PostMan, it runs the code in this method getAllMoneyInTransact instead of the code in this method getAllMoneyInTransactByDate please why is this happening?, I want to retrieve data based on the Date Time filter and not everything. Thank you.

Here is the code.

//moneyInController

const MoneyInData = require('../models/MoneyInData')
const asyncHandler = require('express-async-handler')


// @desc get MoneyIn Transaction
// @route GET '/moneyIn'
// @access Private
const getAllMoneyInTransact = asyncHandler(async (req, res) => {

    const creditTransact = await MoneyInData.find().select().lean()

    if (!creditTransact?.length) {
        return res.status(400).json({ message: 'No rescent transaction' })
    }
    res.json(creditTransact)


})

// @desc get MoneyIn Transaction
// @route GET '/balanceDue'
// @access Private
const getAllMoneyInTransactByDate = asyncHandler(async (req, res) => {
    let startDate = new Date()
    let endDate = new Date()

    startDate.setHours(0)
    endDate.setHours(24)

    const result = await MoneyInData.find(
        {
            createdAt: {
                $gte: startDate,
                $lte: endDate
            }
        }
    ).select('balanceDue').exec()
    console.log(result)


    if (!result?.length) {
        return res.status(400).json({ message: 'No rescent transaction' })
    }
    res.json(result)
    console.log(result)

})

// @desc create MoneyIn Transaction
// @route POST /moneyIn
// @access Private
const createMoneyInTransact = asyncHandler(async (req, res) => {

    const { totalAmountIn, amountRecieved, balanceDue, itemDescription, modeOfPayment } = req.body//newItems
    // const { productName, sellingPriceOfTotal, quantityCount, unitOfQuantity, sellingPrice}= req.body


    //confirm data
    if (!totalAmountIn || !amountRecieved || !balanceDue
        || !itemDescription || !modeOfPayment) {//|| !Array.isArray(newItems) || !newItems.length

        return res.status(400).json({ message: 'All fields are required' })
    }

    const moneyInObj = { totalAmountIn, amountRecieved, balanceDue, itemDescription, modeOfPayment }//newItems

    const newCreditTransact = await MoneyInData.create(moneyInObj)

    //  const newItemCreated = await NewItemsData.create({ productName, sellingPriceOfTotal, quantityCount, unitOfQuantity, sellingPrice,sales: newCreditTransact})

    if (newCreditTransact) {//created
        res.status(201).json({ message: 'New credit Transaction Recorded' })
    }
    else {
        res.status(400).json({ message: 'Invalid credit Transaction' })
    }

})

// @desc update MoneyIn Transaction
// @route patch /moneyIn
// @access Private
const updateMoneyInTransact = asyncHandler(async (req, res) => { })

// @desc update MoneyIn Transaction
// @route patch /moneyIn
// @access Private
const deleteMoneyInTransact = asyncHandler(async (req, res) => { })

module.exports = {
    getAllMoneyInTransact,
    createMoneyInTransact,
    updateMoneyInTransact,
    deleteMoneyInTransact,
    getAllMoneyInTransactByDate
}


//Router
//moneyInRouter


const express = require('express')
const router = express.Router()
const moneyInController = require('../contollers/moneyInController')

router.route('/balanceDue')
      .get(moneyInController.getAllMoneyInTransactByDate)
router.route('/')
      .get(moneyInController.getAllMoneyInTransact)
      .post(moneyInController.createMoneyInTransact)
      .patch(moneyInController.updateMoneyInTransact)
      .delete(moneyInController.deleteMoneyInTransact)
module.exports = router


//Root


root.js
const express = require('express');
const router = express.Router();
const path = require('path');


router.get('^/$|/index(.html)?', (req, res) => {
    res.sendFile(path.join(__dirname, '..','views','index.html'))
} );

module.exports = router;


//Server


require('dotenv').config()
const express = require("express")
const app = express()
const path = require('path')
const errorHandler = require('./middleware/errorHandler')
const cookieparser = require('cookie-parser')
const { logger } = require('./middleware/logger')
const cors = require('cors')
const connectDB = require('./config/dbConn')
const mongoose = require('mongoose')
const { logEvents } = require('./middleware/logger')
const corsOptions = require('./config/allowedOrigin')
const PORT = process.env.PORT || 3500;

console.log(process.env.NODE_ENV)

connectDB()

app.use(logger)

app.use(cors(corsOptions))

app.use(express.json())

app.use(cookieparser())

app.use('/', express.static(path.join(__dirname, 'public')))

app.use('/', require('./routes/root'))// mounts the specified middleware functions at the path which is being specified

app.use('/balanceDue', require('./routes/moneyInRoutes'))

app.use('/moneyIn', require('./routes/moneyInRoutes'))

app.use('/newItems', require('./routes/newItemsRoutes'))

app.use('/users', require('./routes/userRoutes'))

app.all('*', (req, res) => {
  res.status(404);
  if (req.accepts('html')) {
    res.sendFile(path.join(__dirname, 'views', '404.html'))
  } else if (req.accepts('json')) {
    res.json({ message: '404 page not found' })
  } else {
    res.type('txt').send('404 Not Found')
  }
});

app.use(errorHandler)

mongoose.connection.once('open', () => {
  console.log('connected to MongoDB')
  app.listen(PORT, () => console.log(`Server running on port ${PORT}`))

})

mongoose.connection.on('error', err => {
  console.log(err)
  logEvents(`${err.no}: ${err.code}t${err.syscall}t${err.hostname}`, 'mongoErrLog.logs')

})



2

Answers


  1. The route for /balanceDue in moneyInRoutes.js is specified before the route for /moneyIn. In express, routes are matched in the order they are defined. So, when you make a GET request to /balanceDue, it matches the first route (/balanceDue)

    Try this.

    In server.js

    app.use('/moneyIn', require('./routes/moneyInRoutes'));
    app.use('/balanceDue', require('./routes/moneyInRoutes'));
    

    In moneyInRoutes.js

    const express = require('express');
    const router = express.Router();
    const moneyInController = require('../controllers/moneyInController');
    
    router.route('/')
      .get(moneyInController.getAllMoneyInTransact)
      .post(moneyInController.createMoneyInTransact)
      .patch(moneyInController.updateMoneyInTransact)
      .delete(moneyInController.deleteMoneyInTransact);
    
    router.route('/balanceDue')
      .get(moneyInController.getAllMoneyInTransactByDate);
    
    module.exports = router;
    
    

    Watch this doc for reference express routing

    Login or Signup to reply.
  2. You have mounted the moneyInRoutes router to http://localhost:3500/balanceDue here:

    app.use('/balanceDue', require('./routes/moneyInRoutes'))
    

    That means all of your route handlers in moneyInRouter implicitly begin with /balanceDue. This means if you want your getAllMoneyInTransactByDate function to be invoked then you need to post your postman request to:

    http://localhost:3500/balanceDue/balanceDue
    

    At the minute you are posting to http://localhost:3500/balanceDue so inside your moneyInRouter all it matches is the root of the mount path / so it will route to here:

    router.route('/')
          .get(moneyInController.getAllMoneyInTransact)
    

    To avoid any confusion, my advice would be to change your router from this:

    router.route('/balanceDue')
    

    to this:

    router.route('/dueByDate')
    

    then post to

    http://localhost:3500/balanceDue/dueByDate
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search