What is the most efficient way to transfer a value from the main application file to a router file using the express framework

Currently, I am developing an Express application with multiple routes. To ensure modularity, each route will have its own file stored in a dedicated routes folder.

One challenge I encountered is sharing a common value across all routes. Specifically, I need to pass a certain value from my app.js file to a route.js file.

For instance:

//app.js file

const express = require("express");
const app = express();
const port = 3000;
const url = "https://example.com/v1"; // How can I share this value with the test route below?
const test = require("./routes/test")

app.use(express.json());

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
// routes/test.js

const express = require("express");
const router = express.Router();

//Middleware for requests
router.use((req, res, next) => {
  console.log("Time:", Date.now());
  next();
});

router.post("/", (req, res) => {
 console.log(url)
});

Answer №1

app.js I realize that my code is missing app.use("/test", test). Additionally, I should update

const test = require("./routes/test")
to
const test = require("./routes/test")(url)
:

const express = require("express");
const app = express();

const port = 3000;
const url = "https://example.com/v1";

//const test = require("./routes/test")
const test = require("./routes/test")(url);

app.use(express.json());
app.use("/test", test);

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

routes/test.js: My mistake here is the absence of a module.exports

const express = require("express");
const router = express.Router();

module.exports = (url) => {
  router.post("/", (req, res) => {
    res.json({ url: url });
  });
  
  return router;
};

request: To test the code, use the following command:

curl --location --request POST 'http://localhost:3000/test'

Answer №2

To create dynamic routes, you can define them as functions and pass parameters like this:

In your main file:

const v1Routes = require('./routes/v1/');

app.use('/', middleware(), v1Routes({ userid : 123 }));

In your route file:

const routes = require('express').Router({ mergeParams: true })

module.exports = (params) => {
    routes.use('/user', require('./user')(params));
    return routes;
}

In your controller file:

module.exports = (params) => {
    return (req, res, next) => {

        console.log(params.userid)
        res.status(200).json({ message: 'All good' });

    }
}

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

What is the best way to keep track of dynamically inserted input fields?

I've created a form with two text boxes: one for entering people's "name" and another for their "surname." By clicking on the page, you can add additional pairs of text boxes for both "name" and "surname," allowing users to input as many pairs as ...

What is the best way to fill an array within an object using React Hooks?

I am encountering an issue with an object that includes an array. Here is the code snippet in question: const [data, setData] = useState({ jobs: [] }); Currently, I am retrieving data from an API and need to append this fetched information to the jobs arr ...

Unusual behavior exhibited by dynamic code in iframe

When trying to retrieve a dynamic height iframe, I implement the code below. In the <head> area <script language="javascript" type="text/javascript"> function adjustIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight ...

Is it acceptable to include the bundled main.js file in the gitignore for a HUGO project?

Is it possible to exclude the bundled main.js file from a HUGO project by adding it to .gitignore? ...

What is the best way to access an error's body in order to retrieve additional error message details when using the forge-api with nodejs?

I'm struggling to retrieve the body content when an error is returned from the API request. I've attempted creating a bucket with uppercase letters, but all I receive is an error object with statusCode = "400" and statusMessage = "BAD REQUEST". ...

basic computation of whole and decimal values using jquery

I'm having trouble multiplying 2 values in my code where the quantity is an integer and credit price is a decimal number. However, when I run the script, nothing seems to happen. Can someone please help me identify and resolve this issue? Any insight ...

Operating with a multidimensional entity

I am aiming for an object structure like this: {"Red 1":53,"Blue 2":26,"Green 3":25} Based on the following example: I attempted to push data from within .each loop into the object. However, due to its multidimensional nature, I'm uncertain how to ...

Using regular expressions in JavaScript, eliminate all characters preceding a specified final character

I am attempting to eliminate all text that precedes the last character in a Regex pattern. For example: rom.com/run/login.php Would turn into: login.php Can someone guide me on how to achieve this using JavaScript? I have limited experience with regul ...

Error: The name property is not defined and cannot be read in the Constructor.render function

Having trouble building a contact form and encountering an error when trying to access the values. I've checked for bugs in the console multiple times, but it seems like something is missing. Can anyone provide assistance? var fieldValues = { ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...

Managing post requests within the express.js framework

I need assistance utilizing the value provided in a form within Node.js. Here is an example: index.html : <!DOCTYPE html> <html lang="en"> <head> </head> <body> <div align="middle" > <!--Ethernet ...

How can the error within a promise be captured when using resolve()?

Check out the code snippet below: userUpdate(req: Request, res: Response) { this.userTaskObj.userUpdate(req.params.id, req.body).then(() => { res.status(200).json({ status: 'OK', message: 'User updated', ...

clearInterval function is not functioning

Could this be a simple syntax error causing my frustration? The resizeTime variable seems to persist despite multiple attempts to clear it using clearInterval. Any thoughts on what may be going wrong here? Below is the code snippet: var resizeTime; // e ...

Having difficulty breaking down values from an object

Attempting to destructure the data object using Next.js on the client side Upon logging the data object, I receive the following: requestId: '1660672989767.IZxP9g', confidence: {…}, meta: {…}, visitorFound: true, visitorId: 'X9uY7PQTANO ...

Strengthening JavaScript Security

Throughout the past few years, I have delved into various javascript libraries like Raphael.js and D3, experimenting with animations sourced from different corners of the internet for my own learning. I've obtained code snippets from Git repositories ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

Repeating Elements with Angular and Utilizing a Touch Keyboard

Currently, I am developing a table with various fields and the ability to add new rows. The goal is to display all the inputted data at the end. This application is specifically designed for touch screen monitors, so I have created a custom keyboard for in ...

Issue with triggering blur event in Internet Explorer while using Angular 2+

The issue discussed in the Blur not working - Angular 2 thread is relevant here. I have a custom select shared component and I am attempting to implement a blur event to close it when the component loses focus. // HTML <div (blur)="closeDropDown()" t ...

How can we best understand the concept of custom directives using the link method?

As a beginner in AngularJS, I am looking to implement an autocomplete feature for text input. My JSON data is stored in JavaScript and I need help simplifying the process. Can you provide me with a straightforward solution? The specific requirement is to ...

What is the reason behind having several node modules directories within every project?

I'm just starting out with JS development and I have a question about the size of node modules. It seems that when many projects accumulate, we end up having to delete the node_modules folder because it takes up so much space. So, why isn't there ...