What is the best way to show the user's name on every page of my website?

I'm facing an issue where I can successfully capture the username on the home page using ejs after a login, but when transitioning to other pages from the home page, the username is no longer visible. It seems like I am missing some logic on how to handle the username display across all pages.

Thank you in advance for your help!

app.post('/Home', function(req,res){     
    console.log(req.body);
     const check = "select count(*) as cnt from users_info where Name ='"+req.body.userid +"' && Password = '"+req.body.password +"' ";
    mysqlConnection.query(check,function(err,result){
        console.log(result);
        var Records= result[0].cnt;
        console.log(Records);
        if (Records== 1)
        {
            response.render('Login', {username:req.body.userid});
        }
        else
           console.log('User name or Password is invalid');
            //  res.render('Login.ejs', {error: 'User name or Password is invalid'});
    });  
}); 

app.post("/Login/search", (req,response) =>{
    console.log(req.body.search) 
    const check = "select * from users_info where Name NOT LIKE '${req.body.search}%' ";

 mysqlConnection.query(check,function(err,result){
    const arr = result ;
    console.log(app)
    console.log(arr.length)
    let countRecords = arr.length;
    if (countRecords>0){
        const names = arr.map(({ Name }) => Name).join('\n');
        console.log(names.length)
        console.log(names)

        res.render('Login-success', {users:names});

        // res.send(names);
    } else {
        console.log('Request failed...')
    }

});  
});

header.ejs

<body>
         welcome  <%=  username%>

How can I utilize this header file on Home.ejs, search.ejs, and other pages?

Answer №1

To start off, you might want to create a file named "header.ejs".

welcome <%= username%>

Once you have your header file set up, you can easily include it in other web pages using the include command.

<% include header.ejs %>

Just a quick note: Assuming that both the header.ejs file and all other necessary files are located in the same folder for easy access.

Answer №2

If you want to integrate the auth object into your render method, just follow these steps:

res.render('Login-success', { auth: req.session.auth });

Afterwards, you can include a welcoming message like this:

Welcome <%= auth.name %>

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

Utilizing Ajax looping to generate dynamic HTML content with Bootstrap tabs

I am looking for a way to fetch multiple JSON files and display the data from each file in separate Bootstrap 3 Tabs. I understand that the getJSON function does not wait for completion before moving on, but I need help with using callbacks in situations ...

how to pass arguments to module.exports in a Node.js application

I have created a code snippet to implement a Node.js REST API. app.js var connection = require('./database_connector'); connection.initalized(); // I need to pass the connection variable to the model var person_model = require('./mod ...

How can I make the background of a button change when I move my cursor over it

Is it possible to change the background image of a button when hovering over it? Perhaps have the image transition from left to right for a fading effect? Can this be accomplished? ...

Using JavaScript to transform base64 encoded strings into images

I'm currently working on an app using Titanium and I have a base64 string that I need to convert into an image from JSON data. Any assistance you can provide would be much appreciated. Thank you! ...

The Art of Securing Connections in Socket.io

Today, I am embarking on the journey of authenticating a connection through socket.io. The first step involves authenticating the user via a REST API. Once authenticated, I send a JsonWebToken containing the user's username to the client. However, be ...

Setting a cap on file sizes in Azure websites

I am currently attempting to upload a file from the front-end to the back-end and save the file on Azure Storage. My code functions properly when the file size is below 30mb, however, it fails if the file size exceeds 30mb. console.log('- 11111 -&apo ...

Encountering difficulties with managing the submit button within a ReactJS form

As I work on creating a User registration form using React JS, I encounter an issue where the console does not log "Hello World" after clicking the submit button. Despite defining the fields, validations, and the submit handler, the functionality seems to ...

Tips for leveraging the power of Vuetify in Angular versions 7 and 9

I am looking to integrate Vuetify UI Components with Angular using VueCustomElement. While I have successfully integrated Angular and VueCustomElement, adding Vuetify has resulted in errors such as missing $attr and $. However, I am determined to add eithe ...

Can Tailwind CSS be used in conjunction with express's sendFile function?

Attempting to transmit an html file via express but encountering issues with including tailwindcss Ensured correct setup (or so it seems) Could sendFile be unable to send tailwindcss This is the current express setup // express setup const app = express ...

Attempting to instruct my chrome extension to execute a click action on a specific element found within the webpage

I am currently working on developing a unique chrome extension that has the capability to download mp3s specifically from hiphopdx. I have discovered a potential solution, where once the play button on the website is clicked, it becomes possible to extract ...

Adding to and retrieving data from an array

I am relatively new to the world of JavaScript and jQuery, and I have spent the last three days working on a script. Despite my efforts to find a solution by searching online, I have been unsuccessful so far. It seems like my search skills are lacking. My ...

Convert the value of a Javascript variable into a PHP variable

I am feeling confused about how to pass JavaScript variables to PHP variables. Currently, I have a PHP session named example_survey and three buttons with jQuery attributes. When a button is clicked, it triggers a jQuery click event and passes the attribut ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

What is the trick to make the "@" alias function in a Typescript ESM project?

My current challenge involves running a script using ESM: ts-node --esm -r tsconfig-paths/register -T src/server/api/jobs/index.ts Despite my efforts, the script seems unable to handle imports like import '@/server/init.ts': CustomError: Cannot ...

Having trouble retrieving the value of the second dropdown in a servlet through request.getParameter

I am facing an issue with storing the value of the second dropdown in a servlet after utilizing an ajax call in Java to populate it based on the selection made in the first dropdown. While I was able to successfully store the value of the first dropdown ...

Can Mongoose in MongoDB be used to create a real-time search function with Angular controller and form input text for search queries?

Apologies for any language errors and what may seem like a silly question to some, as I am new to programming in Angular, Node, Express, and MongoDB. My query is if it's possible to implement real-time search functionality in the database. I want to ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

Exploring the mechanics of form data handling with node, express, and jade

What are some best practices for processing HTML form data using Express and Jade templates? I was considering implementing a self-calling loop similar to PHP in the router script, where there are two handlers for the same route - one for GET requests and ...

I'm experiencing an issue where using .innerHTML works when viewing the file locally, but not when served from a web server. What could be causing this discrepancy?

Utilizing mootool's Request.JSON to fetch tweets from Twitter results in a strange issue for me. When I run the code locally as a file (file:// is in the URL), my formatted tweets appear on the webpage just fine. However, when I serve this from my loc ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...