I
I
IDONTSUDO2019-05-30 20:33:29
Node.js
IDONTSUDO, 2019-05-30 20:33:29

Express router params() how to pass a function?

I'm trying to set the options for route processing . But express writes.

invalid param() call for userId, got undefined

The express itself in the official documentation simply makes a handler function . Is this a bug or a feature? Or did I write something wrong? If I just declare a function in the future, then it works. But I think maybe there is a better solution?
I tried to point out intentionally
const router = express.Router({mergeParams: true});

But that didn't help
Code.
------------------> routes user.js //роутер
    const express = require("express")
    
    const router = express.Router()
    const { UserById, allUsers } = require("../controllers/user")
    //при помощи деструктаризации вытаскиваем  две функции
    
    router.get('/users',  allUsers) //функция allUsers обслуживает маршрут  /users
    
    router.param('userId', UserById)//то что не работает UserById обслуживает параметры принемаемых запросов
    
    module.exports = router
    ------------------> controllers user.js
    const User = require('../models/user') //подключение mongoose
    
    exports.userById = (req, res , next , id) =>{
        User.findById(id).exec((err, user)=>{
            if(err || !user){
                return res.status(400).json({
                    error: "User nor found"
                })
            }
            req.profile  = user//Вот так функция которую я деструктуризирую  
            next()
        })
    }//дальше ничего интересного
    exports.hasAuthorization = (req, res, next) =>{
        const  authorized = req.profile && req.auth && req.profile._id  === req.auth._id
        if(!authorized){
            return res.status(403).json({
                error: "User is not authorized to perfom this action"
            })
        }
    }
    exports.allUsers = (req, res)  =>{
        User.find(() =>{
            if(err){
                return res.status(400).json({
                    error: err
                })
            }
            res.json({ users })
        })
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Gololobov, 2019-05-30
@dGololobov

router.get('/users', allUsers(req, res))

I
IDONTSUDO, 2019-05-30
@IDONTSUDO

IT'S WORK'S!!!

router.param('userId', function(req,res,id){
UserById(req, res, id)
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question