Is there a way to access a variable declared in index.js from a controller?

Currently, I am experimenting with forms-angular ().

In my index.js file, I have defined a variable called DataFormHandler. However, I am facing an issue trying to access this variable in my controllers. The setter

app.set("formHandler", DataFormHandler)
does not seem to work as expected.

Below is the code snippet:

index.js

'use strict';

var formsAngular = require('forms-angular');  // requiring formsAngular

var kraken      = require('kraken-js'),
        app     = require('express')(),
        options = {
            onconfig: function (config, next) {
                //any config setup/overrides here
                next(null, config);
            }
        },
        port    = process.env.PORT || 8000;

// Initializing FormHandler in index.js and setting it to app for use in controllers.
var DataFormHandler = new (formsAngular)(app);
app.set("fh", DataFormHandler);  

app.use(kraken(options));

app.listen(port, function (err) {
    console.log('[%s] Listening on http://localhost:%d', app.settings.env, port);
});

The assignment app.set("fh", DataFormHandler) is not working as expected. When attempting to retrieve fh in a controller, it returns undefined:

app\controllers\index.js

'use strict';

var UserModel = require('../models/user');

module.exports = function (router) {

    var user = new UserModel();

    router.get('/', function (req, res) {

        var DataFormHandler = req.app.get("fh");
        DataFormHandler.addResource('user', UserModel);

        console.log("DataFormHandler", DataFormHandler);  // undefined

        var model = {
            hello: "Hello"
        }

        res.render('index', model);
    });
};

Could you please advise on how to correctly retrieve a variable in a controller?

Answer №1

After testing out different methods, I stumbled upon a solution that seems to be effective. However, there is some uncertainty as to whether it is the correct approach.

Instead of utilizing

app.set(key, value)

which was unsuccessful for me, I opted for

app.locals.key = value

and surprisingly, this alternative method turned out to work successfully.

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

Using Vue to change select box data separately

I have a functional select box that is currently sending the selected value to a method when the change event occurs. However, I am wondering about something: Let's say I also want to send the cat_id value at the time of selection (to create an objec ...

Tips for uploading files to C# MVC model with the angular file uploader

One of the elements on my webpage is a basic chat client that I developed. Within this chat client, there are topics, messages within those topics, and the messages can also include files. The structure is organized as follows: List of Topics -> Each T ...

ng-include failing to retrieve file name containing UTF-8 character

I encountered an issue with the ng-include directive in the code snippet below. The file name it's trying to access contains a special character, specifically an ñ, resulting in a not found error being displayed. <div ng-include="'{{mainCtrl ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

Position the Bootstrap Modal at the start of the designated DIV

When using a Bootstrap Modal to display larger versions of thumbnails in a photo gallery, there can be some challenges. The default behavior of Bootstrap is to position the modal at the top of the viewport, which may work fine in most cases. However, if th ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

Specify the versions of packages in your package.json file

My package.json file contains many dependencies with "*" as the version, which I have learned is not recommended. I want to update them all to their latest versions. Despite using npm-check-updates tool, it indicates that all packages are up-to-date. Can ...

AngularJS and Select2's Multiple - Tags feature can display tags intermittently, showing some and hiding others as needed

Currently, I am implementing AngularJS along with select2 (not using ui-select). In my view, the following code is present: <select name="rubros" id="rubros" class="select2 form-control" ng-model="vm.comercio.tags" ng-options="rubro.nombre for rub ...

Looking for a way to make the spinner disappear in puppeteer while waiting?

What is the most effective way to wait for the spinner to vanish before clicking on a button? Check out this example ...

Ways to resolve issues with v-model rendering errors

I currently have code fragments within my index.blade.php file that look like this: The content section: . . . <div class="col-12 col-md-12 mb-3"> <label for="attachment" text-muted">Attachment</label> &l ...

Dealing with JSON post requests in Node.js using Express 4

Attempting to develop a basic Express application that accepts JSON through a Post request. The current server-side code is as follows: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); ap ...

Utilizing Restangular to refine search results with filters

I need help troubleshooting an issue with my Restangular query. Despite trying various methods, I am unable to retrieve filtered data successfully. Here are the different approaches I have attempted: $scope.welcomes = Restangular.all("projects").getList({ ...

Is there a similar function in PHP to creating an array with a specified number of elements in JavaScript using "new Array(number)"?

While attempting to convert a basic Javascript function into PHP, I encountered a variable declared as var Variable = new Array (13). In PHP, variables are typically declared like this: $variable = array() But what does the "13" in new Array(13) signify? ...

Updating a field within an array of objects in Node.js and MongoDB: A step-by-step guide

My main objective is to change the value of the field "done" to "true" I am currently working on a project using nodejs Below is the document for reference: { "_id" : ObjectId("5a730e55114dbc2a0455c630"), "email" : "<a href="/cdn-cgi/l/email-protect ...

What is the significance of adding a return statement after calling next() in node.js / Express, and when is it necessary to include

Examining the code snippet below, we can see that req.query is being evaluated to check if its value is equal to name=cat. If this condition is false, next() is triggered to move on to the next middleware function without requiring a return statement follo ...

Performing a series of synchronous JavaScript calls in Node.js by executing GET requests within a for loop

I'm utilizing super-agent in node to interact with a public API and I'm curious if there's a way to make synchronous calls using it. Although I appreciate its automatic caching feature, my research online suggests that synchronous calls are ...

Using Wordpress and JavaScript to dynamically hide a button if a product in the online store does not have an SKU

I'm encountering an issue on my Wordpress site where products with variations are not displaying the inner text on a certain element, despite the fact that the text is present when I inspect the element. Here's the code: const makerBtn = document ...

The art of defining PropTypes for the style attribute in Reactjs

Is there a way to pass the 'style' attribute into my component using JSX syntax? <InputTextWithValidation id="name" style={{width:'100%'}} .../> I'm wondering how I should define the PropTypes for ...

Postpone the inclusion of html files within ng-include in AngularJS

I need to optimize the startup performance of my app by delaying the loading of a series of HTML files that are being included into my main controller. These files are not needed for at least 4 seconds while one specific HTML file processes. How can I de ...

Error message "Encountered an unknown type 'ForOfStatement' when attempting to execute an npm library"

Currently, I am in the process of integrating the PhotoEditor SDK library into my Ruby on Rails project. To achieve this, I have been meticulously following the installation guidelines provided in the official documentation. However, during the setup proce ...