404 Error Route Mapping

I'm encountering some challenges when attempting to access other routes from the index page. While I can access the index without any issues, I receive a 404 error when trying to navigate to any other route. All the other routes are set up similarly, so I'm not sure where the problem lies. Do you have any insights on what might be causing this issue? Thank you.

Below is my app.js file:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var aboutRouter = require('./routes/about');
var workRouter = require('./routes/work');
var projectRouter = require('./routes/projects');
var donateRouter = require('/routes/donate');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/about', aboutRouter);
app.use('/work', workRouter);
app.use('/projects', projectRouter);
app.use('/donate', donateRouter);

// handle 404 errors
app.use(function(req, res, next) {
  next(createError(404));
});

// error handling middleware
app.use(function(err, req, res, next) {
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Next, we have the index.js route:

var express = require('express');
var router = express.Router();

/* GET home page */
router.get('/', function(req, res) {
  res.render('index'){
    if(err){
      console.log(err);
    }
  };
});

module.exports = router;

Here's an example of the new about.js route:

var express = require('express');
var router = express.Router();

/* GET about page */
router.get('/about', function(req, res, next) {
  res.send('about page'){
    if(err){
      console.log(err);
    }
  };
});

module.exports = router;

Lastly, I'm using partials, so here's the header.ejs snippet:

<!DOCTYPE html>
<html>
  <head>
    <title>Africa Foundation</title>
    <link rel='stylesheet' href='/stylesheets/bootstrap.min.css' />
    <link rel='stylesheet' href='/stylesheets/main.css' />
    <script src='/javascripts/fontawesome-all.min.js'></script>

  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="/">
        <img id='af-logo-nav' src='/images/swirl.png'>
        <span>Africa Foundation</span>
      </a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a class="nav-link" href="/about">About <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/work">Our Work</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/projects">Projects</a>
          </li>
          <li class="nav-item">
            <a class="nav-link btn-btn-warning" href="/donate">Donate</a>
          </li>

        </ul>
        <form class="form-inline my-2 my-lg-0">
          <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>
      </div>
    </nav>
    <div class="bg">

Answer №1

In my understanding, the existing code may require you to hit the /about/about route for it to function correctly. Please verify if this solution works, and if it does, modify your app.use('about', aboutRouter) to simply app.use(aboutRouter). This adjustment should ensure that your route functions as intended. The reason behind this modification is that specifying 'about' in app.use establishes a kind of virtual route.

Answer №2

rather than utilizing

res.send("about page")

would you mind adjusting it to simpler names like

"about"

occasionally spaces can cause issues. I believe that could be effective.

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

How to Trigger Individual Pop-up Windows with Different Buttons Using JavaScript

In my HTML file, I have a series of icon images (all with the same class attribute) and an equal number of HTML snippets representing modal/popup windows (also sharing the same class name). These icons and popup snippets always appear in pairs and are gene ...

Error (2322) Occurs When TypeScript Class Implements Interface with Union Type Field

I'm having trouble with error code 2322 popping up unexpectedly. Could you please take a look at this code snippet for me? interface Fish { alive: string | boolean; } class FishClass implements Fish { alive = 'Yes' constructor() { ...

Converting all numbers separated by commas to numbers separated by periods in a string using JavaScript

Imagine a scenario where you have a string containing numbers, such as, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text Your task is to replace the numbers with decimals instead of commas without altering anything else in the ...

What is the best way to transform a List<Pair<String, String>> to a List<String> using JavaScript?

Here is the data output structure: Map<String, List<Pair<String, String>>> "testdata": [ { "1.0": "True" }, { "1.1": "False" } ] ...

HTML dynamic voting system

I'm new to coding in HTML and I have a specific challenge that I need help with. I want to display a value on my webpage that increases every time a user clicks a button. Below is the code I have written so far: <script type="text/javascript& ...

Arranging Objects and Arrays by Two Criteria

Extracting data from an API that provides information in the format below: [ { "id": 173, "date": "2020-12-10T16:05:30", "date_gmt": "2020-12-10T16:05:30", "guid": {}, "modified&qu ...

How can Vue.js deactivate or activate a dropdown based on a checkbox's state?

My task is to toggle the enabled/disabled state of a dropdown called combo-select when a checkbox is checked. The functionality works as expected when I click on Add Name, but not when I am in Editing Name mode and check the box for No Client. https://i.s ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

Easiest method to incorporate dynamic content into a statically generated page using Node.js with Express

Running a static webpage from Node.JS using the Express webserver: app.use('/', express.static('public')); What is the most efficient way to add dynamic content, like a list of items retrieved from a database, to this page? One option ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...

Learn how to configure and utilize an AngularJS factory using ngResource along with passing parameters in the call

As a newcomer to Angular, I'm seeking guidance on creating a new factory utilizing ngResource instead of $http, with the ability to pass parameters. Following an example provided here, I have defined my factory as shown below: app.factory('abst ...

Guide to updating state within a nested object

Is there a way to update nested object states in React using the useState() hook? import React, {useState} from 'react' const MyComp = () => { const [colors, setColors] = useState({colorA: 'RED', colorB: 'PURPLE'}); ...

When accessing a REST API in an Angular 16 project, errors may occur. However, if the API is directly called via POSTMAN or a browser, the expected data will be displayed

angular project using service for data retrieval fetchData() { this.regionService.getAllRegion().subscribe(data => { this.regionValue = data; })} Fetching Data from the API Endpoint getAllRegion(): Observable<RegionI> { const regionUrl ...

When checking for errors with console.log(errors) in Ajax, it may return undefined due to server-side

I'm looking for a way to alert the user about validation errors coming from PHP. I am currently using Laravel 5.3 to build the form and Ajax to retrieve error messages. Below is my JavaScript code: $.ajax({ url: '/artistPost', typ ...

How to Reset Text Fields with a Button Click in Vue.js?

I am currently working on a layout where I need to loop through text fields and buttons. How can I implement a function for each button that clears only the corresponding fields? Take a look at this fiddle here. <div id="app"> <h2>Each text ...

Performing an RxJS loop to retrieve the httpGet response, followed by executing httpPut and httpPost requests based

I am currently working on a UI form that allows users to update or add translation text. To achieve this, I need to create an rxjs statement that will perform the following tasks: Send an httpGet request to the database to retrieve translations in mult ...

"Is it possible to create a single-page website with a unique logo for each div

Is it possible to have a unique logo on each section of my single-page website? Each section has its own div. Check out my website at . Thank you in advance! ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

Setting environment variables using the node command is successful on Linux and macOS platforms, however, it may not function properly

When I clone a project using git, I encounter issues running npm run build on Windows. The command works fine on Mac and Linux: "build": "API=https://dev-api.myexample.com/v1.0 babel-node build.js", An error message is displayed: 'API' is no ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...