Reputation: 1
const express = require('express');
const app = express();
app.use('/', anyroute);
// in anyroute file
router.route('/:id').get(controlFunction)
controlFunction(req, res, res)=> {
// Here we can get the "id" from the variable with req.param.id
}
but I want to use the "id" before getting into this controller function. Like this
modifyFunction(userId)=> {
// Do something with the userId
}
router.route('/:id').get(modifyFunction(id), controlFunction)
Is it possible in express and javascript to retrieve the 'id' from url
and use in modifyFunction(id)
before getting into the request.
In an express middleware req and res variables are transferred from one middleware to next. But I created a function function(type, id) which returns a middleware function(req, res, next). in this function(type, id) type parameter will be passed manually and id from URL.
router
.route('/all-contacts/:id')
.get(authController.isLoggedIn, viewController.getAxiosConfig('contactNameEmail', id), viewController.getAllContact);
exports.getAxiosConfig = (type, id) => {
return (req, res, next) => {
const config = axiosConfig(type, id);
const accessToken = req.cookies.access_token;
const tokenArray = config.headers.Authorization.split(' ');
tokenArray.splice(1, 1, accessToken);
const newToken = tokenArray.join(' ');
config.headers.Authorization = newToken;
req.config = config;
next();
};
};
exports.getAllContact = catchAsync(async (req, res, next) => {
// const token = req.cookies.access_token;
// console.log(token);
// const config = axiosConfig('contactNameEmail');
req.config.method = 'GET';
// const tokenArray = config.headers.Authorization.split(' ');
// tokenArray.splice(1, 1, token);
// const newToken = tokenArray.join(' ');
// config.headers.Authorization = newToken;
const contacts = await axios(req.config);
console.log(req.config);
const { data } = contacts;
res.status(200).render('contactList', {
title: 'All contacts',
data
});
});
Upvotes: 0
Views: 67
Reputation: 89
You can access the ID in the middleware, which is called before the route handler.
Upvotes: 0