The Pug template fails to load when redirecting to a different URL

When I try to redirect to a new URL with query parameters and then render it, the page fails to display. However, if I remove the extra query parameters, the page renders without issue.

These functions are used to verify user logins and display their profile afterward. The intention is for the login function to pass the user's username into the URL, which will then be retrieved by the profile function to populate the profile Pug template.

exports.loginCheck = async (req, res) => {
    let usernameStr = req.body.username;
    let passwordStr = req.body.password;

    var userFound =  await User.findOne()
    .where("username")
    .equals(usernameStr)
    .where("password")
    .equals(passwordStr)
    .select("username email age password answer1 answer2 answer3")
    .then((account) => {
        console.log(userFound);        
        res.redirect(`/profile/${account.username}`);
        
    })
    .catch((err) => {
        console.log(err);
        res.render("login", {
            errorMsg: 'Username and/or password is incorrect.'
            
        });
    });
}



exports.profile = async (req, res) => {
    var param = req.params.userP;

    var userFound =  await User.findOne()
    .where("username")
    .equals(param)
    .select("username email")
    .then((user) => {
        res.render('profile', {
            username: user.username, //I get an error saying cant read '.username', but it will find the user
            email: user.email
        })
    })
    

    

}

The routes:

   app.get('/profile/:userP', routes.profile); //this one doesnt render
   app.get('/profile', routes.profile); //this one does render
   app.post('/profile/login', urlencodedParser, routes.loginCheck); //the post route after users login

All of these routes are meant to render the profile pug template.

I've experimented with params, query strings, adjusting the form routes that post to the profile page, redirecting and rendering in both the login and profile functions. My goal was to send data to the login function via the '/profile/login' route, then redirect to the profile page with the user's details or simply pass the username to the profile page so I could fetch the user's information from my database.

Answer №1

You have a combination of async/await and then blocks in your code:

var userFound =  await User.findOne() //< async/await return value stored in userFound
//..
//..
.then((account) => { //< Return value stored in account
//..

In JavaScript, asynchronous tasks are typically handled with callbacks or promises using either async/await or then blocks. It is recommended to stick to one approach for consistency and clarity. Using async/await with try/catch is considered more readable and offers better error handling.

To improve your code, make the following updates:

exports.loginCheck = async (req, res) => {
    try {
       if(req.body.username === undefined || req.body.password === undefined){
          throw new Error('req.body is empty');
       }
       const usernameStr = req.body.username;
       const passwordStr = req.body.password;
       const userFound = await User.findOne()
       .where("username").equals(usernameStr)
       .where("password").equals(passwordStr)
       .select("username email age password answer1 answer2 answer3");
       if(!userFound){ //< Will be true if userFound == null
          res.render("login", {
             errorMsg: 'Username and/or password is incorrect.'
          });
       }else{ //< userFound has a match so redirect
          console.log(userFound);        
          return res.redirect(`/profile/${userFound.username}`);
       }
    } catch(err) {
       console.log(err);
       res.render("login", {
          errorMsg: 'Internal error on server'
       });
    }
}
exports.profile = async (req, res) => {
   try{
      if(req.params.userP === undefined ){
          throw new Error('req.params is empty');
       }
      const param = req.params.userP;
      const userFound = await User.findOne()
      .where("username").equals(param)
      .select("username email");
      if(!userFound){ //< Will be true if userFound == null
          res.render("login", {
             errorMsg: 'User not found'
          });
      }else{ //< userFound has a match so redirect
         res.render('profile', {
            username: userFound.username,
            email: userFound.email
         });
      }
   }catch(err){
      console.log(err);
      res.render("login", {
         errorMsg: 'Internal error on server'
      });
   }
}

Additionally, please note that this route may not serve its intended purpose:

app.get('/profile', routes.profile);

The route directs to the routes.profile function, but this function expects a request parameter such as req.params.userP.

On another note, there are also security concerns to address. Currently, anyone could potentially access user profiles by guessing usernames in the URL. Consider implementing authentication and authorization measures to secure your routes.

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

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

The jst.js error in sails JS template indicates that the variable _ cannot be found

I am brand new to the world of programming and am currently diving into JavaScript and Sails JS. I must admit, I am enjoying the learning process so far, but recently encountered a problem that has left me scratching my head. Please bear with me as I may n ...

What advantages does Angular Service offer when gathering information compared to utilizing only $http?

Comparing Two Approaches: Approach A. Creating app module Using a service to store model data Implementing a controller to retrieve data from the service File 1: Users.js: angular.module('users', []); File 2: userService.js: angular ...

Rearranging a JSON Object post editing

Currently, I am working on a project where I need to display and sort a list of items based on a JSON object. This includes sorting by both string values and integers within the object. So far, I have been successful in listing and sorting the items by st ...

What is causing Mocha.js to be unable to locate the module?

Having trouble with mocha.js not being able to locate my path! Here's the directory structure I have set up for my node course project: ///////Root --package.json --node_modules/ --playground --server -server.js -db -models ...

Preventing page re-rendering with redux when a condition is not met

I am currently working on a page that features a question paper with multiple options and a button to navigate to the next question. import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import React, { useEffec ...

What is the reason for sending a JSON string in an HTTP POST request instead of a JavaScript object in AngularJS

When sending data via a post request in AngularJS, the code may look like this: $http({ method: 'POST', url: url, data: inputParams, headers: headers }) .then(function succes(response) { successCallBack(response.data); } Here is h ...

Graphs vanish when they are displayed in concealed sections

Looking for a way to toggle between two charts (created with charts.js) by clicking a button? Initially, I had them in separate divs, one hidden and the other visible: <div id="one"> <canvas id="myChart1" width="400" height="400"></can ...

Exploring the Paste Event Data in VueJS

While working on a Vue app, I implemented a paste listener for a textarea to trigger validation code whenever a user pastes data into the field. However, despite being able to see the pasted data in the console under event -> target -> value, I am un ...

Learn how to dynamically swap background images in Vue.js when hovering over different elements

I am facing an issue where I need to change a background image upon hovering over four different elements, with one unique image for each element. Here is what I have attempted: HTML: <div class="projects"> <a v-on:mouseover="hover=myimage1" ...

Error message: "Invalid context validation for CFSELECT tag when utilizing it within a JavaScript function"

When I run CFSELECT normally it works fine, but when I try to include JavaScript inside it, I encounter an error. The normal version works as expected. <tr id='selectionDropdown'> <td >Non-Keyword Traffic:</td> <t ...

What is the best way to have DOMDocument processed in PHP after running Javascript?

Currently, I'm working on a program that searches for tags. Unfortunately, I'm encountering difficulties retrieving tags created with JavaScript. ...

Trouble with reading from a newly generated file in a node.js program

Whenever I launch my results.html page, I generate a new JSON file and use express.static to allow access to the public folder files in the browser. Although my application is functioning properly, I find myself having to click the button multiple times f ...

The jQuery click event appears to be malfunctioning

Attempting to create a basic calculator using jQuery, the code seems straightforward but nothing is happening when executed. It's as if the JavaScript file isn't linked properly. Below is the jQuery code snippet: function addNumber(num){ ...

Error message: "The URL retrieved from the JSON data is being displayed as undefined in a

I encountered an issue while following this tutorial. I am attempting to load an image from a JSON-formatted URL. Despite following the tutorial correctly, I am unable to get the image to load. Upon using react-tools, I noticed that the url field is displ ...

What are some methods for incorporating functions and libraries from Node.js into my JavaScript code?

Does anyone know how to connect functions from Node.js to JavaScript? I am attempting to use the mongoose library in JavaScript, but the browser does not support the "require" function. Can someone please assist me with this? ...

The results of the Mongoose aggregation $lookup operation are coming back as an empty array in the 'as' field

Suppose we have two datasets: Order and Seller for a platform similar to Ebay where customers can purchase items from individual sellers. Every Order includes a seller field that indicates the ID of the shop owner. const orderSchema = new mongoose.Schema( ...

Using jQuery to retrieve individual sentences from a paragraph

I'm facing a challenge trying to identify the two shortest sentences from a collection of paragraphs. The structure of the paragraphs is as follows: <p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.< ...

Conceal the Tab Bar in Stack Navigator Excluding the tabBarVisible Setting

I discovered some solutions using outdated versions of navigation, specifically involving the "tabBarVisible" option in Tab Navigator. However, this option is no longer available, so I am seeking guidance on how to hide the Tab Bar on specific screens with ...

Converting information from a model into individual variables

I'm a newcomer to typescript and angular, and I've been attempting to retrieve data from firebase using angularfire2. I want to assign this data to variables for use in other functions later on. I am accustomed to accessing object members using d ...