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
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
In moneyInRoutes.js
Watch this doc for reference express routing
You have mounted the
moneyInRoutes
router tohttp://localhost:3500/balanceDue
here:That means all of your route handlers in
moneyInRouter
implicitly begin with/balanceDue
. This means if you want yourgetAllMoneyInTransactByDate
function to be invoked then you need to post your postman request to:At the minute you are posting to
http://localhost:3500/balanceDue
so inside yourmoneyInRouter
all it matches is the root of the mount path/
so it will route to here:To avoid any confusion, my advice would be to change your router from this:
to this:
then post to