'Error while passing multiple middlewares in Edit Route
I am getting the following error when I try to pass multiple middlewares in my Edit route.
The error is:
Route.put() requires a callback function but got a [object Object]
This is the code:
const auth = require('../middleware/auth')
const admin = require('../middleware/admin')
router.put('/inflow/item/:id', [auth, admin],async (req, res) => {
const brand = await Brand.findOne({ brand: req.body.brand })
const existingItem = await Stocks.findById(req.params.id)
const item = {
'productname' : req.body.productname,
'quantity' : existingItem.quantity + req.body.quantity,
'brand' : brand._id,
}
const logChanges = {
'quantityAdded' : req.body.quantity,
'author' : 'Peter'
}
console.log(logChanges)
const update = {
$set : item,
$push : {logAddition : logChanges}
}
console.log(item)
const stocks = Stocks.findByIdAndUpdate(req.params.id, update,{new: true}, (err, updateListing) => {
if(err){
res.status(404).send({success: false, msg: err.message})
}
console.log(updateListing)
res.json(updateListing)
})
})
The error disappears when I remove one of the middlewares. Like this:
router.put('/inflow/item/:id', [auth, admin],async (req, res) => {
}
Below are the code snippets for auth and admin middlewares:
Auth
const jwt = require('jsonwebtoken')
const config = require('config')
module.exports = function (req, res, next){
const token = req.header('x-auth-token')
if (!token) return res.status(401).send('Access Denied. No token provided')
res.status(401)
try {
const decoded = jwt.verify(token, config.get('jwtPrivatekey'))
req.user = decoded
next() // we either terminate process or we pass control
}catch(ex){
res.status(400).send('Invalid Token', ex.message)
}
}
Admin
module.exports = function(req, res, next) {
//401 Unauthorized - no json webtoken
//403 Forbideen - you tried again but still cannot access
if(!req.user.isAdmin) return res.status(403).send('Access denied')
next()
}
Solution 1:[1]
Either you haven't shared the complete code of the edit route controller. Or you forgot to export the router object in the controller file.
router.put('/inflow/item/:id', [auth, admin],async (req, res) => {
}
// I think you've missed this line
module.exports = router;
Read more on defining and using separate route modules.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amit |
