Route all Express JS paths to a static maintenance page

Need help with setting up a static Under construction page for an Angular Web App with Express Node JS Backend. I have a function called initStaticPages that initializes all routes and have added a new Page served via /maintenance.

However, when trying to redirect to /maintenance using a middleware on all routes, I encounter too many redirects error causing the web app to go down. Redirecting on all routes except "/" works, but it's not the desired behavior. Any suggestions on how to resolve this issue would be greatly appreciated. Thank you!

router.js

const initStaticPages = (router) => {
  router.use('/', checkMaintenanceMode, express.static('public'))
  router.use('/main', checkMaintenanceMode, requireAccess, express.static('public'))
  router.use('/login', checkMaintenanceMode, express.static('public'))
  router.use('/logout', checkMaintenanceMode, express.static('public'))
  router.use('/logout?reason=timeout', checkMaintenanceMode, express.static('public'))
  router.use('/requestHistory', checkMaintenanceMode, requireAccess, express.static('public'))
  router.use('/recurringRequest', checkMaintenanceMode, requireAccess, express.static('public'))
  router.use('/maintenance', express.static('public'))
}

module.exports = () => {
  const router = express.Router()
  initStaticPages(router)
  return router
}

An example of a simple Middleware:

const checkMaintenanceMode = (req, res, next) => {
    res.redirect('/maintenance/')
}

main.js

const app = require('express')()
const router = require('./router')()
const cookieParser = require('cookie-parser')
const compression = require('compression')

const port = process.env.PORT

app.use(compression())
app.use(cookieParser())
app.use(router)

app.listen(port, () => console.log(`Running on port ${port}`))

Encountering a second error after rearranging routes: Failed to load module script: Expected a JavaScript module script but the server responded with MIME type text/html. Strict MIME type checking is enforced for module scripts per HTML spec.

Further details on content within public folder and maintenance container are provided below.

/app/frontend/app/container/maintenance: 
   maintenance.component.css
   maintenance.component.html 
   maintenance.component.ts
   
/app/server/public: 
   assets 
   index.html
   vendor-es2015.3f2dce1d421f11b1eba1.js
   vendor-es2015.3f2dce1d421f11b1eba1.js.map
   vendor-es5.3f2dce1d421f11b1eba1.js
   vendor-es5.3f2dce1d421f11b1eba1.js.map
   polyfills-es5.34831379c55aac23d35e.js
   polyfills-es5.34831379c55aac23d35e.js.map
   main-es2015.730bc485b11bbd634316.js
   main-es2015.730bc485b11bbd634316.js.map
   polyfills-es2015.8c0828ece2f5d1fedbfb.js
   polyfills-es2015.8c0828ece2f5d1fedbfb.js.map
   main-es5.730bc485b11bbd634316.js main-es5.730bc485b11bbd634316.js.map
   runtime-es2015.dc25f63d6f9e75106165.js
   runtime-es2015.dc25f63d6f9e75106165.js.map
   runtime-es5.dc25f63d6f9e75106165.js
   runtime-es5.dc25f63d6f9e75106165.js.map 
   3rdpartylicenses.txt
   jsoneditor-icons.15f2789dd231f36d43a4.svg
   styles.9211410addacf27114df.css styles.9211410addacf27114df.css.map

Answer №1

This seems to be a case of specificity being important in defining routes. It is crucial that your routes are arranged from most specific to most general.

/ is a route that will match any URL, including /maintenance. So when any route hits /, it then redirects to /maintenance which matches with / and creates a cycle.


  router.use('/main', checkMaintenanceMode, requireAccess, express.static('public'))
  router.use('/login', checkMaintenanceMode, express.static('public'))
  router.use('/logout?reason=timeout', checkMaintenanceMode, express.static('public'))
  router.use('/logout', checkMaintenanceMode, express.static('public'))
  router.use('/requestHistory', checkMaintenanceMode, requireAccess, express.static('public'))
  router.use('/recurringRequest', checkMaintenanceMode, requireAccess, express.static('public'))
  router.use('/maintenance', express.static('public'))
  router.use('/', checkMaintenanceMode, express.static('public'))

Just a side note: I rearranged the /logout routes using similar logic. This may not directly address the issue at hand, but thought it was worth mentioning.

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

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...

Unit testing in AngularJS: Initializing the controller scope of a directive

Here is the code for a directive with a separate controller using the "controller as" syntax: 'use strict'; angular.module('directives.featuredTable', []) .controller('FeaturedTableCtrl', ['$scope', function ($sco ...

Transforming nested arrays into a string quickly

I'm currently facing an issue where nested arrays parameters passed from a React App to an Express Server via axios are being converted into strings on the server-side. The client-side and URL format seem correct, but the problem occurs when the neste ...

Share a status on Facebook with an earlier date

How to Modify Facebook Post Date using Graph API facebook facebook-graph-api I am able to publish on my wall using the Graph API. By utilizing FB nod and graph, I now need to post on Facebook with a date from the past Afterwards, I can adjust the date man ...

Attempting to retrieve data either by code or with a WHERE condition proves unsuccessful as the data retrieval process yields no results

Seeking assistance with my Angular project that is utilizing a Node.js server and MSSQL express. I am having trouble retrieving data using a WHERE condition in my code. Any help in identifying the missing piece or error would be appreciated. Thank you. // ...

What is the best way to create a new row at a specific index in an ng-repeat loop?

My Goal: I am aiming to insert a new row of ul after every 2 elements in my ng-repeat loop. For example: <ul class="col-sm-2"> <li><p>Automobile & Motorcycle</p></li> ...

"Enhance Your Website with qTip2 Feature to Load Multiple AJAX Sites Simult

I'm currently utilizing the qTip2 library for my project and I've implemented their AJAX retrieval functions following this example: http://jsfiddle.net/L6yq3/1861/. To enhance my query, I have modified their HTML to include multiple links. The ...

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

How does Ruby on Rails facilitate interactions between multiplayer users and visitors?

I am looking to create a way for visitors to interact on my website. Imagine a virtual chat space. This involves collecting and sharing data among users, which can be accomplished using ajax or similar methods. However, I'm wondering if there are ex ...

What is the best way to consistently display a scroll bar at the bottom?

How can I ensure that the scroll bar is always at the bottom when loading pages? I need an immediate solution. The JavaScript code seems to be malfunctioning. Please assist me in resolving this issue. #student_name{ height:315px; } <div id ...

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

Tips for customizing the border radius style of the menu in Vuetify's v-autocomplete component

I am looking to customize the appearance of the drop-down list in the v-autocomplete component by adding a border-radius style, as depicted in the image below. The current design I have achieved closely resembles the visual shown below. Previously, I app ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

It can be challenging to manage numerous if-else conditions in JQuery

I am having trouble with my JQuery code that checks multiple conditions. No matter what I enter, it always goes to the else condition. $(function() { $('#installment').on("keydown keyup", check); function check() { var inst = Number($( ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

How can you access and utilize the inline use of window.location.pathname within a ternary operator in

I need assistance with writing a conditional statement within Angularjs. Specifically, I want to update the page to have aria-current="page" when a tab is clicked. My approach involves checking if the tab's anchor href matches the current window' ...

Why isn't this ajax script able to successfully transmit the data?

I'm having some trouble sending a JavaScript variable to a PHP file in order to create a query. Here's the script I've been using, but unfortunately it doesn't seem to be working. Any assistance would be greatly appreciated. <select ...

Having trouble retrieving the data property from the parent component within the child component slot

I am facing an issue with my Vue components. I have a rad-list component and a rad-card component. In the rad-list component, I have placed a slot element where I intend to place instances of rad-card. The rad-card component needs to receive objects from t ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...