Obtain a 404 rendering using EJS in an ExpressJS application

Utilizing express ejs on both my backend and frontend, I have set up a route to display the dashboard on the admin page. However, when attempting to access my URL http://localhost:3000/admin, I am encountering a 404 error when trying to render the view. Here is an overview of my code setup:

In app.js

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 admin = require('./routes/admin');

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('/admin', admin);

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

// Error handler
app.use(function(err, req, res, next) {
  // Set locals for error message
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // Render the error page
  res.status(err.status || 500);
  res.render('error/404');
});

module.exports = app;

dashboard controller dashboard.js

exports.getDashboard = (req, res, next) => {
    res.render('dashboard', {
        pageTitle: 'Dashboard',
        path: 'admin/page/dashboard'
    });
};

Admin route in admin.js

const path = require('path');

var express = require('express');

const adminController = require('../controllers/backend/dashboard');

var router = express.Router();

/* GET users listing */
router.get('/admin', adminController.getDashboard);

module.exports = router;

If anyone can provide assistance with this issue, I would greatly appreciate it. Thank you.

Answer №1

If you have already set up a route for /admin in app.js and again in admin.js, it will be accessible at localhost:3000/admin/admin.

To fix this issue, update your admin.js file with the following code:

const path = require('path');

var express = require('express');

const adminController = require('../controllers/backend/dashboard');

var router = express.Router();

/* GET users listing. */
router.get('/', adminController.getDashboard);

module.exports = router;

Answer №2

The issue lies in this section:

const adminController = require('../controllers/backend/dashboard');

The problem is that the controller dashboard does not have a default export, so you will need to use curly braces like this:

const { adminController } = require('../controllers/backend/dashboard');

Please give this a try and inform me if it works! :)

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

Sending an object to a Vue 2 component and confirming its validity

I am working with a Vue component that has numerous props. <Field v-for="field in fields" :key="field.name" :name="field.name" :type="field.type" :label="field.label" :values="field.values" :value ...

Determining the height of child elements within a React component

One challenge I'm facing inside a React component is the need to calculate the total height of my child containers, specifically the three h3 elements, in order to accurately determine the height of my parent div during a transition animation. While I ...

`vuetify sidebar with a nested menu``

I am trying to enhance the vuetify sidebar menu I created by adding a submenu to a specific title. Despite editing the code and data as shown below, I am unable to see any changes reflected. Below is the code snippet: <v-list flat class="mt- ...

Issues with comparing dates

I'm attempting to compare two different dates: Start Date Thursday, October 29th, 2015 at 6:00 PM GMT End Date Friday, October 30th, 2015 at 12:00 AM GMT Simply put, if(end > start) { alert('It works'); } else { alert(&apo ...

Guide to developing JavaScript code that moves information from one local website to a different one

Here's the scenario: You input text into a field on website A and click a button. Upon clicking that button, the entered text should appear in website B. I attempted to use localStorage for this functionality, but unfortunately it was not successful. ...

Error: Unable to access the toISOString property of an undefined object

https://i.sstatic.net/jtZnQ.png import './ExpenseItem.css'; function ExpenseItem(props){ return ( <div className="expense-item"> <div>{props.date.toISOString()}</div> <div className="expen ...

The router is displaying the component directly on the current page rather than opening it on a separate page

The issue is that the router is rendering the page on the same page instead of generating a new one. When clicking on the Polls link, it only renders the page there but the URL changes in the browser. Polls.js import React from 'react'; import ...

A guide to sorting an object with integer keys by its values using JavaScript

I am facing an issue with sorting a map by values instead of keys. No matter what I do, it always ends up getting sorted by the keys. On the server side, I have a map that is already sorted. When I send this map to JavaScript using JSON, it gets re-ordere ...

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

Tiny adjustment to jQuery Collapsible Panel

I have successfully implemented a jQuery Accordion in my demo. When I click on 'About Us', it reveals the 'Team' link below. Exciting! Now, I am wondering if it is possible for this Accordion to function without needing the 'item& ...

To enhance your React Class Component, make sure to utilize the withStyles feature when

This particular component is not set as a default export component. I am attempting to apply some styles to it but struggling to figure out how to encapsulate it in an HOC. Hence, the current issue where it does not recognize the classes variable. import ...

Refreshing ApolloClient headers following a successful Firebase authentication

I am encountering an issue while trying to send an authorization header with a graphql request when a user signs up using my React app. Here is the flow: User signs up with Firebase, and the React app receives an id token. User is then redirected to ...

Automatically pre-fill and send hidden form

I'm working on a form and have set up a handler for the submit button like this: $( '#submit_btn' ).click( function( data ){ theForm = document.getElementById( 'realForm' ); theForm.meetingName.value = document.getElement ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

Hidden Document Scroll Offset

When CSS is used to hide scrollbar html, body { width: 100%; overflow-x: hidden } The above code snippet removes the scroll from the window but triggers it on the body element. To calculate the scroll values in such cases, you can use: pageOffset = ...

The concept of AJAX send function and toggling button visibility

I am facing a challenge with a textarea and send button on a panel that is displayed after entering the first character. The visibility of the button is controlled by the isButtonVisible() method. Once clicked, it sends the text from the textarea using the ...

Guide on establishing a connection to a TCP server through Node.js and Socket.io from a client

I am currently encountering a major issue. There are two Node.js applications that I am working with, one being an Express app and the other a worker process. I need assistance in ensuring that when the worker process is running, it sends data to the Exp ...

Interacting with an element within a jQuery dialog box created through a function click

I'm encountering an unusual issue with jQuery and Javascript across all browsers (IE, FF, Chrome). On my (asp.net) webpage, I have the following structure: A header with numerous dynamically generated buttons at PreRender A hidden div containing but ...

Creating objects with nested objects in Express using Async: A step-by-step guide

Looking to create an object called user with sub-objects (authData, nameData, and emailData) in a synchronous manner has been successful. As an exercise, I wanted to explore implementing this using async. However, I am struggling with the syntax required f ...

I am encountering an issue where my CSS file does not load when my application is deployed on Heroku. Just as a heads up, I am utilizing

After deploying my app on Heroku using Node.js, Express, and EJS, I encountered a problem where the CSS is not loading properly. Error Details : Unchecked runtime.lastError: The message port closed before a response was received. Refused to apply style f ...