How can you pass a DB object in a multi-router setup with ExpressJS?

Is there a way to pass the db object from index.js to api1 and api2 in ExpressJS?

I have multiple router settings set up like the example in the documentation, with index.js, api1, and api2. How can I achieve this?

I attempted using:

app.use('/api/v1', require('./controllers/api_v1')(db));

However, it resulted in errors showing:

Router.use() requires a middleware function but got an Object

Here is a snippet of my index.js:

var express = require('../..');
const knex = require('knex');
const config = require('./config');

var app = module.exports = express();
const db = knex(config.db);

app.use('/api/v1', require('./controllers/api_v1'));
app.use('/api/v2', require('./controllers/api_v2'));

app.get('/', function(req, res) {
  res.send('Hello from root route.')
});

/* istanbul ignore next */
if (!module.parent) {
  app.listen(3000);
  console.log('Express started on port 3000');
}

Content of api_v1.js

var express = require('../../..');

var apiv1 = express.Router();

apiv1.get('/', function(req, res) {
  res.send('Hello from APIv1 root route.');
});

apiv1.get('/users', function(req, res) {
  res.send('List of APIv1 users.');
});

module.exports = apiv1;

And here is api_v2.js

var express = require('../../..');

var apiv2 = express.Router();

apiv2.get('/', function(req, res) {
  res.send('Hello from APIv2 root route.');
});

apiv2.get('/users', function(req, res) {
  res.send('List of APIv2 users.');
});

module.exports = apiv2;

Answer №1

To ensure easy access to the database object, export it from a database.js file and then require it in both the index.js file and any other file that requires database access. Alternatively, albeit less elegant, you could make the variable global by using global.db = db. This way, you can utilize db throughout your Node.JS application seamlessly.

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

jQuery - Incorrect folder path for image replacement

I have a specific request to change the image paths in multiple .html pages, redirecting them from the default folder to another folder. After implementing code from an external javascript file successfully, I am encountering an error where the HTML sou ...

A command-line style text input box in HTML

I am currently developing a unique text box that enables the execution of custom commands using a customized syntax. This concept is intended to help teach programming to children. For example, when a user types a $ sign, the program responds with an aler ...

Mocha and Chai together form the perfect combination, but unfortunately, there is a

I encountered an issue with mocha and chai. The errors in my tests are not displaying properly when they fail (for example, showing 'a' was expected to be 'b'). Here is a link to the test log 1) Shouldn't publish new post - there ...

Leveraging Template Variables for Styling in Vue 3's CSS Classes

Struggling to find the perfect way to utilize variables returned by Vue functions in CSS inline styles, specifically with the "width" style. I have two variables that are returned to the template and can be used with the {{}} syntax, but not directly as a ...

Exploring the Process of Passing Data with MongoDB's find().count()

Currently, I am working on developing a straightforward Express application with MongoDB. I have set up an endpoint that searches for a user by their name and then displays the relevant data stored in the database on the page. While attempting to incorpora ...

What is the best way to swap out every instance of an array?

There are two arrays that I'm working with, The first array is defined as var symbols = ['A', 'B'];, and the second array is defined as var num = ['3', 'A', '5', '4']; I am looking for a so ...

Python Mechanize: choosing a selection

Can you help me with selecting an option from a select tag? In this particular form, there is only one select tag and no submit button. The purpose is that when an option is chosen, it triggers the javascript function __doPostBack('D1','&ap ...

What could be the issue with the setup of my express.js route configuration?

I am currently dealing with a server that routes requests using Express. One of the routes I have set up is as follows: productRouter = ProductRouter app app.use '/', productRouter app.use '/products/(videocloud|perform)/*', p ...

Jquery code fails to execute unless a breakpoint is set

I'm encountering a strange issue with the jquery star rating plugin. It seems that only when there's a breakpoint in my JS code will the radio buttons transform into stars; otherwise, they remain unchanged. Let me break down the code step by step ...

Struggling to loop through a child in Firebase real-time database?

I'm struggling to retrieve a nested child from my database with the following structure https://i.stack.imgur.com/ZDs38.png I am attempting to get the URI from the Gallery object. When I log in, I can see this in the console https://i.stack.imgur.c ...

Installing and running Node.js within a tomcat server

After creating a web application using Angular, Node/Express, and MySQL, I faced an issue with deployment. My Angular app is running on a tomcat server connected to multiple PCs, but now I need to also deploy my backend (Node.js/Express.js) on the same s ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

Display multiple items from a JSON object in Django on the following page

I need to implement a feature that allows users to select multiple entries from a JSON object displayed in an HTML table. After selecting their entries and submitting, they should be redirected to a new page where only their chosen items are shown for conf ...

Setting up a Progressive Web App installation feature with a built-in delay from a

I have integrated a v-dialog component that shows up when my webapp loads and is utilized for installing the PWA: <template> <div> <v-dialog v-model="popupAndroid" max-width="80%" ...

How to transfer data using props through the ":to" attribute of a router link in Vue.js

I am facing an issue with creating a router-link in Vue and passing a route name as a prop. What I am trying to achieve is the following: <template> <div> <router-link :to="myProps">Login</router-link> </div> </tem ...

Is there a way to successfully include an apostrophe in a URL?

I am currently utilizing Node.js: var s = 'Who\'s that girl?'; var url = 'http://graph.facebook.com/?text=' + encodeURIComponent(s); request(url, POST, ...) This method is not functioning as expected! Facebook seems to be c ...

The use of anonymous arrow functions results in Fast Refresh not maintaining local component state

I am facing an issue with the code in my pages/index.js file: import React from 'react'; import dynamic from 'next/dynamic'; const TVChartContainer = dynamic( () => import('../components/TVChartContainer').then ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

Utilize JavaScript on the browser to cache videos, potentially exceeding 10 minutes in length, directly

Currently, I am experimenting with WebRTC and looking to share a video stream with multiple peers. To optimize this process, I believe it would be beneficial to cache certain parts of the video. After exploring Cache Web APIs, I found them to be less effe ...

Detect if the user is using Internet Explorer and redirect them to a different

My web application is having trouble rendering in Internet Explorer. In the meantime, I would like to detect if the user is using IE and redirect them to a different page specifically for IE visitors. What is the best way to accomplish this? Should I use ...