Having trouble navigating the maze of Express routing

app.js file

// home route
app.get("/home", async(req, res)=>{
    let allCards = await  Card.find({});
    let skills = await Skill.find({});
    res.render("index", {allCards, skills});
})


// add new skill route
app.get("/home/newskill", (req, res)=>{
    res.render("newskill");
});

// submiting a new skill to the database
app.post("/home/newskill", async(req, res)=>{
    let {title, image}= req.body;
    let newskill = new Skill({
        image: image,
        title: title
    });
    await newskill.save();
    res.redirect("/home");
})


// signup route
app.get("/home/signup", (req, res)=>{
    res.render("signup.ejs");
});

// signup 2nd route
app.post("/home/signup", async(req, res)=>{
    let {userName, email, password}= req.body;
    let newUser = new User({
        userName: userName,
        email: email,
        password: password
    });
    await newUser.save().then(res =>{console.log(res)}).catch(err =>{console.log(err)});
    res.redirect("/home");
})


// login route
app.get("/home/login", (req, res)=>{
    res.render("login.ejs");
});

// login second route
// app.post("/home/login", async(req, res)=>{
//     let {userName, email, password} = req.body;
//     let user = await User.findOne({email: email, password: password})
//     res.render("index.ejs", {user});
    
// })

html login file


<div id="main">
    
    <form action="/home/login" method="post">
        <h3>Please input your login info</h3>
        <br>
        <input type="email" name="email" placeholder="Enter your email">
        <br><br>
        <input type="password" name="password" placeholder="Enter Password">
        <br><br>
        <button class="btn btn-light">Submit</button>
    </form>


</div>

index.ejs file

<% for( let skill of skills) { %>
                <div>
                    <img src="<%= skill.image %>" alt="">
                    <p><%= skill.title %></p>
                </div>
            <% } %>

I'm currently undertaking a project involving user authentication and I've run into an issue with implementing another login route in my application. The error message 'cannot get skill' appears when attempting to add this route. However, removing the second login route eliminates the error. Can someone provide me with a basic explanation of why this error occurs and offer guidance on routing principles to prevent similar issues in the future? Any assistance would be highly appreciated!

Answer №1

It is quite puzzling that the error disappears when the second login route is commented out, as it does not seem to contain any errors. The error message "cannot get skill" should typically appear when attempting to access the "/skill" route, but it appears this route may not be included in your server code at all. I recommend reviewing your code to ensure that you are not inadvertently trying to access this route somewhere.

Answer №2

When handling the login post route (the second login route), remember to pass the necessary skills data while rendering the index.ejs file. If you forget to do so, make sure to redirect to the /skills route or include the skills during the rendering process after logging in.

Answer №3

When setting up your initial route, make sure to utilize the GET method and send the login.ejs page. The variable skills is not currently being used on the login.ejs page, so there should not be any errors:

app.get("/home/login", (req, res)=>{
    res.render("login.ejs");
});

The second route involves a POST request that sends the index.ejs page along with data stored in the user variable:

app.post("/home/login", async(req, res)=>{
   let {userName, email, password} = req.body;
   let user = await User.findOne({email: email, password: password})
   res.render("index.ejs", {user});  
})

It's worth noting that the index.ejs page always expects a variable named skills to be present. When making a post request to /home/login, the skills variable won't exist like it does when doing a GET request via app.get("/home",...)

To handle this situation, consider using an if statement within your index.ejs file, similar to the following:

<%if (skills) { %>
   <% for( let skill of skills) { %>
      <div>
         <img src="<%= skill.image %>" alt="">
         <p><%= skill.title %></p>
      </div>
   <% } %>
<% } %>

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

What is the best way to style output in jQuery for a specific div?

I have developed a tool for creating forms, but I am struggling to format the output neatly like pretty print. I have tried using \n and pre tags as well. allCont += "<label>"+insCleaned+"</label><input type='text' name= ...

The $routeChangeSuccess event is failing to trigger in ngNewRouter in AngularJS version 1.4

Transitioning from AngularJS 1.3 to AngularJS 1.4 has brought about some changes, including the use of AngularJS's new route method known as ngNewRouter, specifically introduced in AngularJS 1.4. Below is a snippet of my code: var versionModule = ng ...

Is it possible for PHP to dynamically load a file based on a condition set in JavaScript?

I am attempting to dynamically insert a PHP include onto the page once the user scrolls to a specific part of the page. Is this feasible? For example: var hasReachedPoint = false; $(window).scroll(function() { var $this = $(this); if ($this.scrollTo ...

Refreshing a Nested Component Within a Parent Component in React

Currently, I am in the final stage of a small project where a Higher Order Component (HOC) is being utilized to display a basic Tinder-like application. The internal component is a class-based component containing its own fetch() call that presents user d ...

Does vuetify have a v-autocomplete callback for when there is no filtered data available?

Is there a method to detect when the v-autocomplete component in Vuetify.js displays "no data available" after filtering? I have searched the events documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events Is there a workaround for this iss ...

Using nested ternary operations in React can cause issues with accessing local variables

Note: I encountered an issue where the extra curly braces around the first ternary result did not solve my initial problem. I replaced them with parentheses. Josep's suggestion to use getTime required me to equate the dates. The Date().setHours(0, 0, ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

Error encountered while installing npm packages (express, ember)

Recently, I've been attempting to set up ember and express on my Windows 8.1 system for educational purposes. However, I encountered a similar error with both packages while running the command below: npm install -g express-generator To provide bett ...

What is the best method for updating a nested array within another nested array in an object using MongoDB?

There is a similarity between my issue and the one mentioned in this discussion LINK. However, my problem differs in the following way: { "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"), "comments": [{ "na ...

Guide to retrieving and editing images from Appwrite using Vue

Currently, I am utilizing a View frontend to retrieve a PDF file from Appwrite Storage. My goal is to acquire the PDF, insert additional text onto it, and then save it to the user's local device. Below is the code I have so far - although I can recei ...

Methods for retrieving and persisting the data from a particular row within a table using JavaScript or jQuery

Is there a way to store the selected row values of a table in an array of arrays using JavaScript / jQuery? Check out this JSFiddle I believe that we should listen for the event when the 'Show selected' button is clicked. For instance, in Java ...

"Vue3 offers the ability to return a multi-layer object through the Provide-Inject

While implementing provide-inject in my personal project, I encountered an issue where the value returned by inject() was a RefImpl Object. This meant that I had to access the actual value using inject().value.value instead of just inject().value. Here is ...

React Native: Unable to update React state during logout process

Currently, I am working on a mobile app and learning new practices in React every day as a junior developer. Today, I need assistance with implementing a User Logout function. In my Profil.js file, I have the Logout function inside an IconButton that gets ...

What is the best way to calculate the total sum of a column in Vue JS?

https://i.sstatic.net/K8Rqj.png To manually add a row, each row is stored in the "items" array items: [ { occuGroup:'', constType:'', bfloorArea: 0, cfloorArea: 0 }, ], Below is the code I wrote to calculate the to ...

Error encountered when using the Jquery append function: Anticipated ')' issue

While working on my PHP file, I encountered an issue with an AJAX request. The request is returning the correct value, however, when attempting to use the append function in jQuery, it results in an error being displayed in the console. $.ajax({ ...

Tips for efficiently exporting and handling data from a customizable table

I recently discovered an editable table feature on https://codepen.io/ashblue/pen/mCtuA While the editable table works perfectly for me, I have encountered a challenge when cloning the table and exporting its data. Below is the code snippet: // JavaScr ...

Converting the basic logic from if-else statements to foreach loops was unsuccessful

I am currently working with this function: const applyColor = (value) => { let color //shallow to dark const colors = ['#B3E5FC', '#81D4FA' ,'#4FC3F7', '#29B6F6', '#03A9F4', &ap ...

Looking for assistance in setting a new initial state for a javascript toggle on page load

Need assistance with customizing the Youtube-TV JS plugin for a client website? The current setup loads the player with a playlist in an open state, but the requirement is to load it with the toggle closed, displaying the array of playlists instead. If y ...

Customize Popover Color in SelectField Component

Looking to customize the SelectField's popover background color in material-ui. Is this possible? After exploring the generated theme, it seems that there is no option for configuring the selectField or popover. Attempted adjusting the menu's ba ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...