Retrieving variables using closures in Node.js

I have been developing thesis software that involves retrieving variables within closures.

Below is the code snippet written in node.js:

var kepala = express.basicAuth(authentikasi);
// authentication for login

function authentikasi(user, pass, callback) {
    // declare MongoDB database
    db.collection('ak_teacher', function (err, data) {
        data.findOne({
            'tch_name': {
                '$regex': user
            }
        }, function (err, level) {

            console.log(level); // monitor data

            if (level == null) {
                console.log('Headmaster's database value entered as Null, please retry login');
                callback(null);
            } else {

                var a = level.tch_name;
                var b = level.tch_password;

                var c = level.sch_id; // (need this variable for next code)

                var result = (user === a && pass === b);
                console.log("School ID : " + c);
                callback(null /* error */ , result);
            }
        });
    });
};

var tes = authentikasi(); // (I am unsure how to declare to retrieve my variable c)

app.get('/siswa_2', kepala, function (req, res) {
    // using variable here
    var sch_id = tes;
    console.log("School ID in query: " + sch_id);
    console.log('Displaying all student data');
    db.collection('ak_student', function (err, collection) {
        collection.find({
            "sch_id": sch_id
        }).toArray(function (err, items) {
            console.log(items);
            res.send(items);

        });
    });
});

I am attempting to access the variable c.

Answer №1

To retrieve the value of c, you must pass it into the callback like this:

callback(null /* error */, result, c);

After that, call authentikasi in the following manner:

// Note, since "c" is passed as the third argument in the callback,
// this is how we assign it to "tes"
//                                             |
//                                             |
//                                             V
authentikasi(user, pass, function(unused, result, tes) {
  app.get('/siswa_2', kepala, function(req, res) {
    var sch_id = tes;
    console.log("id school in query: " + sch_id);
    console.log('Displaying all student data');
    db.collection('ak_student', function(err, collection) {
      collection.find({"sch_id": sch_id}).toArray(function(err, items) {
        console.log(items);
        res.send(items);
      });
    });
  });
});

Answer №2

Based on information from the documentation, the correct approach is to return a user object in the callback function. You can easily include your c variable in that object:

var kepala = express.basicAuth(authenticate);

function authenticate(user, pass, callback) {
    // initialize my MongoDB database
    db.collection('ak_teacher', function (err, data) {
        data.findOne({
            'tch_name': {
                '$regex': user
            }
        }, function (err, level) {
            console.log(level); // keep track of data

            if (level == null) {
                console.log('School head database value entered as Null, please log in again');
                callback(null);
            } else {
                var a = level.tch_name;
                var b = level.tch_password;
                var c = level.sch_id; // (i need this variable for next code) 

                if (user === a && pass === b) {
                    console.log("School ID: " + c);
                    callback(null, {name: a, id: c});
//                                 ^^^^^^^^^^^^^^^^
                } else
                    callback(null, false);
            }
        });
    });
};
// Do not attempt authentication outside of the request context

app.get('/siswa_2', kepala, function (req, res) {
    var sch_id = req.user.id;
//               ^^^^^^^^^^^
    console.log("ID school in query: " + sch_id);
…
});

Answer №3

Another technique you can explore is utilizing locals:

The local variables in the response are limited to the request, meaning they are only accessible to the view(s) rendered during that specific request / response cycle. Otherwise, this functionality is the same as app.locals.

This feature is valuable for revealing request-specific data like the request pathname, authenticated user, and user settings.

If you assign c to res.locals.c, you should be able to utilize it in subsequent elements of that particular request and following response instances.

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

Experiencing difficulty retrieving the variable within a NodeJs function

Currently, I am utilizing the NodeJS postgresql client to retrieve data, iterate through it and provide an output. To accomplish this, I have integrated ExpressJS with the postgresql client. This is a snippet of my code var main_data = an array conta ...

What distinguishes submitting a form from within the form versus outside of it?

When the code below, you will see that when you click btnInner, it will alert 'submit', but clicking btnOuter does not trigger an alert. However, if you then click btnInner again, it will alert twice. Now, if you refresh the page: If you first ...

Can CoffeeScript Preserve the Identity of Multiple `this` Objects?

I find myself in a rather unique situation that I haven't encountered before, and I'm struggling to find relevant information on how to handle it. So, I decided to seek advice here in hopes of sparking a productive discussion on the matter. Curr ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Guide on accessing data from Infrared sensors sent to a local host via an Arduino with the help of jQuery

Currently, I have a setup where Infrared sensors are connected to an Arduino board. These sensors transmit the value of 1 when no object is detected and 0 when an object is present. To monitor these sensor readings, I have successfully created an HTTP web ...

When using jQuery with a large selectbox, you may encounter the error message: "Uncaught RangeError: Maximum

My select box works fine in IE and Mozilla, but throws an uncaught rangeError in Chrome when choosing the "Others" option to display a second select box with over 10k options. How can I diagnose and resolve this issue? <!DOCTYPE html> ...

Issue with implementing MUI Grid within a dialog across various screen sizes

While working with a MUI dialog and MUI grid, I encountered an issue. The code I am using is directly from the website, with only minor modifications to the dialog function names and the box wrapping the dialog. Despite changing the size of the dialog, t ...

Error: The object identified as #<Object> does not support the 'Router' method in node

Hey there! I've been trying to follow a tutorial on creating Chat Roulette using Node.js, Socket.io, and OpenTok from this link. After successfully installing express, I updated the code in my Package.json file as per the tutorial with the following: ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

Node.js Express returning a 404 error

I am currently in the process of developing an express application Here is the content of my app.js file: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = req ...

phpif (the current date is after a certain specific date, do

Can someone please help me solve this problem? I want to prevent echoing a variable if the date has already expired. Currently, my PHP code displays: Match 1 - April 1, 2015 Match 2 - April 8, 2015 What I need is for Match 1 to not be echoed if the cur ...

Is history.pushState capable of more than just making an xhr request?

I've hit a roadblock in my current project. The issue I'm facing is getting a registration page to load. The XHR request is returning the output of the PHP code, which is causing problems. My goal is to have it load as a document rather than an ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

Unique Javascript Library Focused on AJAX

Looking for a specific JavaScript library that focuses solely on AJAX functionality, such as a basic XMLHttp wrapper. ...

Autocomplete feature integrated within search bar

I'm currently experimenting with merging MUI autocomplete and MUI searchbar to create a Searchbar that provides suggestions. I have attempted the following: https://codesandbox.io/s/material-demo-forked-cthpv import React from "react"; impo ...

Node.js passport is prone to failures in handling URLs

After integrating Passport for Facebook login on my website, I'm facing an issue where the callback from Facebook always redirects to the failureRedirect URL even though I receive all the data and valid tokens from Facebook. Any suggestions or insight ...

Using TypeScript to Implement Content Security Policy Nonce

I encountered an issue with my TypeScript Express project while attempting to implement a CSP Nonce using Helmet. app.use(helmet.contentSecurityPolicy({ useDefaults: true, directives: { scriptSrc: ["'self'", (req, res) = ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Crop box overlaying video background

Utilizing jCrop to establish a crop region for a video element. My goal is to make the video section within the crop area fill a container with identical proportions, but I'm encountering challenges with the mathematical calculations. The sizes of th ...