Ways to obtain parameter from URL in Express without diving into the request object

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
}

however, my goal is to utilize the 'id' before entering this controller function. This can be achieved like so

modifyFunction(userId)=> {
// Perform actions using the userId
}

router.route('/:id').get(modifyFunction(id), controlFunction)

Can I retrieve the 'id' from the URL using Express and Javascript and use it in modifyFunction(id) prior to handling the request?

In an Express middleware, the req and res variables are passed from one middleware to another. Nevertheless, I have created a function named function(type, id) which produces a middleware function (req, res, next). In this function(type, id), the type parameter is manually provided while the id is extracted from the 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
  });
});

Answer №1

The middleware allows you to retrieve the ID before reaching the route handler for easy access.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Asynchronous function nested within a loop

Hello there! I am currently working on converting a SQLite database to NeDb using the following code snippet: const sqliteJSON = require('sqlite-json'); const Datastore = require('nedb') const exporter = sqliteJSON('etecsa.db&apo ...

Make an element in jQuery draggable but always within the viewport

My issue is that when I resize the window, the element stays in its position until I start dragging it. Once I drag it and then resize the window again, it doesn't stay within its container. To better illustrate my problem, you can view a demo on Fid ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

Obtaining the translated text from the script in Vue JS using Vue Translate

My code currently looks something like this: <template> <div> {{ text }} </div> </template> <script> export default { data: () => ({ text: 'Hello world' }) } </script> I am tryin ...

Multer in Node.js: Memory remains occupied after uploading and processing images

I have been utilizing Sharp and Multer in Node.js, however, I am encountering memory issues. It seems like the buffer used is not being released once the process is completed with this particular code : var storage = multer.memoryStorage(), upload = mul ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Combining objects in JavaScript

I am currently working on converting the object received from the server into a format compatible with the backend system. I have a received object that looks like this { 'User.permissions.user.view.dashboard': true, 'Admin.permissio ...

I encountered an issue when attempting to obtain the local issuer certificate for https://registry.yarnpkg.com

I encountered an error message stating unable to get local issuer certificate while trying to execute yarn add <anything>. Oddly enough, everything was working fine yesterday, but today this issue popped up seemingly out of nowhere with no recollect ...

Setting environment variables using the node command is successful on Linux and macOS platforms, however, it may not function properly

When I clone a project using git, I encounter issues running npm run build on Windows. The command works fine on Mac and Linux: "build": "API=https://dev-api.myexample.com/v1.0 babel-node build.js", An error message is displayed: 'API' is no ...

The Next.js API call for /api/contact was successful, but no response was sent back, potentially causing delays in processing other requests

Encountering the issue of API resolved without sending a response for /api/contact, this may result in stalled request on a specific API route within Next.js. Despite successfully sending emails using sendgrid, I am unable to receive a response to handle e ...

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

One issue encountered in the AngularJS library is that the default value does not function properly in the select element when the value and

In this AngularJS example, I have created a sample for the select functionality. It is working fine when I set the default value of the select to "$scope.selectedValue = "SureshRaina";". However, when I set it to "$scope.selectedValue = "Arun";", it does n ...

What is the best way to conditionally wrap a useState variable in an if statement without losing its value when accessing it outside the if block in reactjs?

I am facing a coding challenge with my cards state variable in React using the useState hook. I tried adding my array data to it but ended up with an empty array. Placing the state inside an if statement resulted in undefined variables. I attempted various ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

I am interested in creating a Discord bot that can send interval messages

I am trying to set up a discord bot that sends a message at regular intervals, like every 10 minutes. However, I keep running into an error. Can someone please assist me with this issue? (Apologies for any language errors in my message) Below is the code ...

What is the cause behind the mongoose populate function delivering an irregular array and how can it be resolved?

I'm currently using mongoose's populate function to retrieve and populate a list of data like this: Account.findOne({_id:accountId}).populate({ path:"orders.order", match:{_id:orderId}, selecte:'', ...

Transitioning between states in React with animation

In my React application, I have a menu that contains a sub-menu for each item. Whenever an item is clicked, the sub-menu slides in and the title of the menu changes accordingly. To enhance user experience, I aim to animate the title change with a smooth fa ...