The hyperlinks in the navigation bar are leading me to incorrect destinations

I am currently developing an authentication app and facing an issue with the navbar links for register and login. They are not redirecting me to the correct destination. These links work perfectly on the landing index page, but not on any other page.

site with functional links

same site where the links are broken

app.js

var app = express();

var mongoose = require("mongoose");
var bodyParser = require("body-parser");


var users = require("./routes/users.js");


app.use(bodyParser.urlencoded([{extended:false}]));
app.set("view engine","ejs");

app.use(express.static("public"));



app.get("/",function(req,res){
    res.render("index");
});

app.post("/hello",function(req,res){
    res.redirect("/");
});

app.use("/users",users);


app.listen(3000,function(){
    console.log("server has been started!!!");
}); 

routes/users.js

var router = express.Router();


router.get("/login",function(req,res){
    res.render("login");
});

router.post("/login",function(req,res){
    res.send("hello from login");
});

router.get("/register",function(req,res){
    res.render("register");
});

router.post("/register",function(req,res){
    res.send("hello from post");
});

module.exports = router;

views/partials/header.ejs

<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/style.css" rel="stylesheet">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    </head>
    <body>
<nav class="navbar navbar-default">
  <div class="container">
    <ul class="nav navbar-nav navbar-right">
        <li><a href="users/register">Register</a></li>
        <li><a href="users/login">Login</a></li>
        <li><a href="/logout">Logout</a></li>
    </ul>
  </div>
</nav>

views/index.ejs

<div class="container">
<div class="jumbotron">
    <h1>Welcome to Index page</h1>

    <p>Authentication test app</p>
</div>
</div>
<%- include('partials/footer')%>

views/register.ejs


<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control input-form" id="exampleInputEmail1" placeholder="Email" name="email">
  </div>
    <div class="form-group">
    <label for="exampleInputUsername">Username</label>
    <input type="text" class="form-control input-form" id="exampleInputUsername" placeholder="Username" name="username">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control input-form" id="exampleInputPassword1" placeholder="Password" name="password">
  </div>

  <button type="submit" class="btn btn-default">Submit</button>
</form>

<%- include('./partials/footer')%>

views/login.ejs


<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control input-form" id="exampleInputEmail1" placeholder="Email" name="email">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control input-form" id="exampleInputPassword1" placeholder="Password" name="password">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

<%- include('./partials/footer')%>

Answer №1

It is important to remember to add a slash to the hrefs in the views/partials/header.ejs file. Here's an example:

<li><a href="/users/register">Register</a></li>
<li><a href="/users/login">Login</a></li>

Explanation:

When using users/login, it will attach the path to the current document level instead of the root of the site. For instance, if you are at the URL localhost:3000/users, the href users/login will result in localhost:3000/users/users/login, while the href /users/login will lead to localhost:3000/users/login

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

Styling the arrow of a CSS select box

Is it possible to place a dropdown arrow inside a select box? I have tried, but the arrow always displays behind the select box. How can I modify the CSS code to position the arrow properly inside the select box? .form-item-custom-search-types::before { ...

Interactive Node.JS Terminal

Today, while experimenting with the npm package, I realized that all my commands were being executed from my local command prompt on the machine instead of through the node.js command line provided in the download. So, my question is: why have a node comm ...

The issue I am facing with this self-closing TITLE tag causing disruption to my webpage

I am encountering a problem with my basic webpage. <html> <head> <title/> </head> <body> <h1>hello</h1> </body> </html> When viewed in both Chrome and Firefox, the webpage ...

What are the reasons for not accessing elements in a more "direct" way like elemId.innerHTML?

Recently, I came across a piece of JavaScript code that accesses HTML elements using the shorthand elementID.innerHTML. Surprisingly, it worked perfectly fine, but interestingly, most tutorials opt for the traditional method of using document.getElementByI ...

I am a beginner in vue.js and I am currently experimenting with posting and retrieving values in a cross-platform environment. However, I am encountering an error while

Trying to make a CORS-platform API call using post and get methods in Vue.js to register data. Note: The API call must be cross-platform. Encountering the following issue: The response to a preflight request does not pass access control check: No &apo ...

Performing an Ajax request to submit a form without the need to reload the page in MVC

I am looking for assistance with submitting a form from an MVC view without refreshing the page. However, it seems that my AJAX code below is not functioning properly: //here is ajax call function AjaxCallAndShowMessage(btnClick) { $('form').s ...

Encountering TOO_MANY_REDIRECTS issue while attempting to iFrame a Kibana dashboard with cookies

I'm currently working on integrating password-protected Kibana dashboards into an iFrame within my Node-powered Express application, as discussed in this forum thread. The Kibana setup involves X-Pack for protection and mandates user login to access v ...

The Correct Way to Implement Return in jQuery Ajax

Encountering an issue with the login form where I am unable to proceed to the next page after entering my credentials. The system acknowledges if the email and password match, however, the login does not go through. Seeking assistance in identifying the ...

SVG path with dynamic elements

Consider the following SVG: <svg xmlns="http://www.w3.org/2000/svg" width="237" height="129" viewBox="0 0 237 129" fill="none"> <path d="M228 1H9C4.58172 1 1 4.58172 1 9V91V104V127L20 111.483L228 112C232.4 ...

"Enhance Your Design with Hovering CSS Backgrounds

Seeking assistance with changing the background image on span hover. If anyone can assist, I have included the complete code for the website below. Take a look at the full website code here: Pastebin CSS Pastebin JavaScript ...

Display only alphabetic characters in the text field

I have a jQuery function that I am working on: $('#contact_name').on('input', function() { var input=$(this); var re =/^[A-Za-z]+$/; var is_email=re.test(input.val()); if(is_email) { } else { } }); This function is targeted at the fol ...

Is it possible to pass a PHP array to JavaScript without using Ajax?

Currently, I have a JavaScript function that utilizes Ajax to fetch an array of data from PHP and dynamically populates a dropdown menu. Everything is functioning as expected. However, I am beginning to feel that using Ajax for this task might be a bit ex ...

Unable to retrieve observable modifications

In my code file for handling reports, named report.service.ts, I have a method that retrieves reports data. This method simply returns a constant array of report objects from a mock source. Here is the implementation: @Injectable() export class ReportServ ...

What is the best way to pass query strings from React to the backend?

import React, { useEffect, useState } from "react"; import { Form, Row, Col, Button } from "react-bootstrap"; import { useParams, useNavigate } from "react-router-dom"; const FilterComponent = ({ categories, brands }) => { ...

Node.js variable initialization

Here's the issue I'm facing: in this function, I'm attempting to return an array of objects. When I use console.log within the forEach loop, the array is populated as expected. However, just before my return statement, it appears empty. http ...

Utilizing a single controller in multiple locations within AngularJS

I am currently working on developing an Ionic application which includes screens with lists containing checkboxes and the option to select all items. My experience with AngularJS and Ionic is fairly limited. The "Select All" functionality works as intende ...

Tips for highlighting the final word in the headline using an underline

I'm attempting to create a title style similar to what is shown below https://i.sstatic.net/Qao4g.png The issue I'm facing is achieving the underline effect. I tried using title:after but it didn't give me the exact result I'm looking ...

What strategies can be employed to minimize redundant re-rendering of React components while utilizing the useEffect hook?

Hey everyone, I'm facing a challenge in my React/Electron project where I need to minimize renders while using the useEffect hook to meet my client's requirements. Currently, I have a container/component structure with an index.js file that house ...

Tips on implementing loops in promises

Struggling to execute a for loop within a promise, I suspect the issue lies in where to call resolve but unsure. /* * Retrieve user conversations * @param user {String} */ function getConversations(user){ return new Promise(function(resolve, reject){ va ...

Attempting to create an OutlinedInput with a see-through border, however encountering strange artifacts

https://i.sstatic.net/PL30l.png Struggling to achieve a TextField select with outlined variant and a see-through border. Here's the current theme override I'm using: overrides: { MuiOutlinedInput: { root: { backgroundColor: &ap ...