Understanding the functionality of app.locals within app.get in an Express application and how to effectively parse data

I am currently developing a parse application using express. In my index file, I want to display different information to users based on whether they are logged in or not. However, I am facing an issue with storing the flag and logged-in user name using app.locals. Here is the code snippet from my app.js:

// The homepage renders differently depending on whether user is logged in.
app.get('/', function(req, res) {
if(Parse.User.current()){

  Parse.User.current().fetch().then(function(user) {
     // Render the user profile information (e.g. email, phone, etc).
     name = user.get('username');
  });
  app.locals({flag :true,name:name});

}else{
  app.locals({flag:false, name:''});
}
// Render a public welcome page, with a link to the '/' endpoint.
  var ProfessionalUsers = Parse.Object.extend("User");
  var query = new Parse.Query(ProfessionalUsers);
  query.limit(50);
  query.equalTo("usertype", "Professional");
  query.find().then(function(profs) {
    res.render('index', {
      title: "Popular Experts",
      profs: profs,
    });
  });



});

Here is the code written in my index file:

<div class='navigation'>
    <ul class='navigation-ul'>
        <li><a href='/' class='search' id='searchLink' >Search</a></li>
        <% if(flag){ %>
        <li><a href='/dashboard' class='dashboard' id='dashboardLink' >Dashboard</a></li>
        <% } %>
        <li><a href='/howitworks' class='how-it-works' id='howItWorksLink'>How it Works</a></li>
        <li><a href='/testimonials' class='testimonials' id='testimonialsLink' >Testimonials</a></li>
        <li><a href='/faqs' class='faqs' id='faqsLink'>FAQs</a></li>
        <% if(flag){ %>
        <li><a href='/logout' class='logout' id='logoutLink'>Logout<span class='username'>(<%= name ? name : '' %>)</span></a></li>
        <% }else{ %>
        <li><a href='/login' class='login-signup' id='navLoginSignupLink'>Login/Signup</a></li>
        <% } %>


    </ul>

</div>

This section of code displays the professionals:

<p><%= title %gt;</p>
 <div class='professionals'>

 <% for(var i=0;i<profs.length;i++) { %>

<div class='professional'>

    <div class='picture-space' onclick = 'location.href = "/user/<%= profs[i].id %>"' style='cursor:pointer'>
      <img src='images/default.jpg'/>
    </div>
      <div class='name-space'><%= profs[i].attributes.username %></div>
      <div class='service-space'><%= profs[i].attributes.servicetype %></div>
      <div class='linkedin-space'><a href='http://<%= profs[i].attributes.linkedin %>' target='_blank'>Linkedin Profile</a></div>


</div>
<% } %>
</div>

After making some changes, here is the updated code:

// The homepage renders differently depending on whether user is logged in.
app.get('/', function(req, res) {

// Render a public welcome page, with a link to the '/' endpoint.
  var ProfessionalUsers = Parse.Object.extend("User");
  var query = new Parse.Query(ProfessionalUsers);
  query.limit(50);
  query.equalTo("usertype", "Professional");
  query.find().then(function(profs) {
    var user = Parse.User.current();
    if(user){
      user.fetch().then(function(user,error) {
        res.render('index',{user:user.toJSON(),profs:profs,title:'Popular Experts'});            
      });
    }else{
      res.render('index', {
      title: "Popular Experts",
      profs: profs,
      user:''
    });
    }


  });  

  });

Answer №1

When using app.locals, keep in mind that it does not have access to the req and res objects. This feature is designed for storing non-dynamic data that remains constant throughout requests, such as the app's name. If you need to work with request-specific data, consider utilizing res.locals (http://expressjs.com/api.html#res.locals) instead.

To achieve your desired outcome, I recommend incorporating middleware tailored to your needs.

You can apply this middleware exclusively to a specific route. It will be executed immediately before the designated function for that route:

function getUserInfo(req, res, next) {
   var user_name = "adam"; //Retrieve user data here

   //Expose 'user_name' variable to the view
   res.locals.user_name = user_name;

   next(); //Proceed to the next middleware, defined by you.

}

//Include getUserInfo as middleware for the '/' route, running before your custom middleware. Your middleware will trigger upon calling 'next()'.
app.get('/', getUserInfo, function(req, res) {

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

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

What is the best way to handle parsing JSON using external middleware after the removal of body parser in Express?

Having trouble parsing JSON with external middleware after Express removed the body parser? I used to rely on Express bodyParser for handling JSON posts, but after updating Express, my JSON requests are returning null. It seems like I was using the wrong ...

When working with the Google Sheets API, an error occurred: "this.http.put(...).map is not a valid

Having difficulty with a straightforward request to the Google Sheets API using the PUT method. I followed the syntax for http.put, but an error keeps popping up: this.http.put(...).map is not a function. Here's my code snippet: return this.http ...

Is it possible to make an element draggable after it has been prep

Seeking assistance with making a notification draggable when added to a webpage. The notifications are housed in a parent div named notification_holder Here is the structure: <div class="notification_holder"> <div class="container"><b ...

Top method for implementing dynamic routing in Express.js (node.js)

I am currently in the process of developing a straightforward CMS using express.js that can dynamically generate routes based on JSON data retrieved from a database. Here is an example of the JSON structure: pagesfromdb = { home = { paths = [& ...

Error: Node.js encountered an unexpected identifier in the syntax

I'm encountering an issue with my web application. The error keeps popping up. app.get("/campground/:id/comments/new",function(req,res){ camp.findById(req.params.id)({ if(err) console.log(err); else ...

To compare two JSON files that contain identical values but different keys in order to generate a consolidated table

My goal is to create a comprehensive table by merging data from two different JSON files. One file contains names, work positions, and ages, while the other file includes emails, names, and job roles. The challenge lies in the fact that they use different ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

"Uncovering the parent element with jQuery: A step-by-step guide

I need help increasing the font size of a parent element without affecting the entire body's font size. How can I achieve this? For example, with the id="vs-1", I want to increase the font size of the grandparent li text here which is "1940". $("li ...

Node unable to interpret accented characters from CSV file input

Currently, I am utilizing npm fast-csv as my CSV reader/writer tool. It offers a simple and straightforward way to handle CSV files. My goal is to use this tool along with iconv to deal with "accented" characters and non-ASCII characters by converting them ...

There seems to be an issue with accessing the / endpoint in node

index.js const path = require("path"); const express = require("express"); const exp = require("constants"); const dotenv = require("dotenv").config(); const port = process.env.PORT || 5001; const app = express(); //enable body parser app.use(express.jso ...

What is the best way to ensure that my program runs nonstop?

Is there a way to have my program continuously run? I want it to start over again after completing a process with a 2-second delay. Check out my code snippet below: $(document).ready(function () { var colorBlocks = [ 'skip', 'yell ...

Nothing remains after the fall: coding void

I am facing an issue where my item becomes null after being dragged 2-3 times and dropped in a different place. I have included my code below and I can't seem to figure out where the mistake lies. Can you please review it and let me know what needs to ...

Switch Bootstrap Tab

I have successfully implemented a bootstrap tab on my webpage and it is functioning as intended. Now, I am interested in adding an additional feature to the tabs. My question is, is it possible to toggle the content area if the same tab is clicked again? ...

Storing information in local storage as JSON using AngularJS

I am working on a form with the following fields: <form ng-submit="addState()"> <input ng-model="text1" type="text"> <input ng-model="text2" type="text"> <input ng-model="text3" type="text"> ...

Testing the number of times module functions are called using Jest

As someone who is relatively new to JavaScript and Jest, I am faced with a particular challenge in my testing. jest.mock('./db' , ()=>{ saveProduct: (product)=>{ //someLogic return }, updateProduct: (product)=>{ ...

Generating a string indicating the range of days chosen

Imagine a scenario where there is a selection of days available to the user (they can choose multiple). The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday ...

Version 13 of the Discord slash command encounters an "interaction failed" error

After implementing the slash commands in Discord v13 as per the instructions on discordjs.guide, I encountered an issue when trying to use the commands - interaction failed. Here is a snippet of my code: // Here goes the code const { Client, Collection, ...

Encountered an issue while compiling code using the Istanbul plugin

I'm currently working on generating a code coverage report for my ReactJS project using the babel-istanbul-plugin. However, when I incorporate "istanbul" as a plugin in my .babelrc file and attempt to build, I encounter the following error: ERROR in ...

Configuration file stored within the node_modules directory

I have developed a generic npm package that contains my business logic. However, I require access to some information stored in my google cloud storage configuration files. How can I retrieve this data when my package is located within the node_modules fol ...