Answer the question
In order to leave comments, you need to log in
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
const router = express.Router({mergeParams: true});
------------------> 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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question