Utilize Express.js routes to deliver static files in your web application

I am looking to serve a collection of HTML files as static files, but I want the routes to exclude the .html extension.

For example, when someone visits example.com/about, I'd like it to display the contents of about.html

In my research on serving static files, it seems that removing the file extension from the URL might not be easily achievable. Am I correct in my understanding, or is there something I may have overlooked?

Answer №1

To deliver your static file, make sure to utilize the router system

app.get('/product', function(req, res) {
    res.render('product.html');
});

Prior to this step, establish a middleware for the html rendering engine

If dealing with numerous static files, consider using a middleware for seamless functionality

https://www.npmjs.com/package/fresh-urls

Answer №2

If you want to create a simple middleware function that can only process specific preset names, you can do so easily. Any route not matching those preset names will simply go to your normal routes:

// Define the static file lookup table with desired names
var staticFiles = ["about", "index", "home"].reduce(function(obj, item) {
    obj["/" + item] = true;
    return obj;
}, {});

app.use(function(req, res, next) {
    // Check if the requested path is in the lookup table
    // If yes, append ".html" and send the corresponding file from the base directory
    // You can use any source directory for these files
    if (staticFiles[req.path]) {
        res.sendFile(path.join(__dirname, req.path + ".html"));
        return;
    }
    next();
});

Note: This method ensures that only specific files are served, preventing unauthorized access to your file system through other URLs.


Here's an example implementation where the files are served from a subdirectory named "html" below the base directory:

app.use(function(req, res, next) {
    if (staticFiles[req.path]) {
        res.sendFile(path.join(__dirname, "html", req.path + ".html"));
        return;
    }
    next();
});

In node v0.12+, you can utilize the Set object to hold your list of static routes like this:

var staticFiles = new Set(["/about", "/index", "/home"]);

app.use(function(req, res, next) {
    if (staticFiles.has(req.path)) {
        res.sendFile(path.join(__dirname, "html", req.path + ".html"));
        return;
    }
    next();
});

Answer №3

To streamline the organization of multiple static pages on your website, consider consolidating them under a single route named static.js. This can be achieved by:

module.exports = function () {
var router = require('express').Router();

var pages = {
    'about-us': 'path/to/about-us',
    'contact-us': 'path/to/contact-us'
};

router.get('/:page', function (req, res, next) {
    if (!pages[req.params.page]) {
        return next();
    }

    res.render(pages[req.params.page]);
});

return router;
};

Integrate this route into your application using app.use(require('./static')()); to optimize page loading and navigation.

Answer №4

Give this a shot.

app.use(express.static(path.join(__dirname, 'xyz')));

In this code snippet, replace 'xyz' with the name of the folder you want to serve as static content. The folder's name should be relative to the root of your application.

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 generate a static header in nextJS?

I am looking to create a static navbar without needing client-side fetching. Currently, I am using Apollo GraphQL and my _app.js file is set up like this: import React from 'react'; import Head from 'next/head'; import { ApolloProvider ...

Does JavaScript automatically round large numbers?

I have a simple array: myArray = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},] However, when I append the values from thi ...

Removing nested divs using JavaScript

My website has a nested div structure which contains multiple child divs. Here is an example of the div structure: <div id="outside-one"> <div class="inside" id="1"></div> <div class="inside" id="2"></div> <div ...

Refreshing div with updated form/content using jQuery and AJAX

Is it possible to use jQuery/AJAX functions to replace a form (or any content) with another form when a button is clicked, without reloading the page? Essentially creating a multi-part form dynamically. Can I achieve this with the following code snippet? ...

Scroll-triggered Autoplay for YouTube Videos using JQuery

Issue: I'm trying to implement a feature where a YouTube video starts playing automatically when the user scrolls to it, and stops when the user scrolls past it. Challenges Faced: I am new to JavaScript web development. Solution Attempted: I referre ...

`Switching between two buttons: A guide`

Here is the codepin: https://jsfiddle.net/magicschoolbusdropout/dwbmo3aj/18/ I currently have a functionality in my code that allows me to toggle between two buttons. When I click on one button, content opens and then closes when clicked again. The same b ...

What is the best way to send a socket object to a route in your code?

My objective is to enable users to send friend requests with a simple click, directing the request to the intended recipient. Currently, I am facing two issues: 1. How can I pass the socket object to a router without enclosing the router within io.on(&ap ...

Production pages encounter 'get' error when refreshed due to routing issues - Node.js, Express API with webpack and ReactJS frontend

I have set up my webpack configuration to compile my react app, and I am using Node.js as the server with Express middleware. Whenever I try to refresh a route on the production environment, for example /chefs, I receive an error. Below is my server.js s ...

Configuring Node.js and express.js for my personal website to showcase my projects

I am new to node.js and I'm excited to implement it on my personal website as a way to start learning. I have successfully set up the node server, but I am struggling with setting up routing using express.js. All my files are typical static files like ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...

Transferring information from a React Native app to a Node.js server using Express

Looking for advice on transferring data between React Native and Node.js (Express)? I'm currently developing an app using React Native and Node.js with Express, but struggling to establish communication for data exchange. Any tips would be greatly ap ...

What could be the reason behind encountering an NaN error while using these particular functions?

I recently delved into the world of JavaScript, starting my learning journey about two months ago. While going through a few tutorials, I stumbled upon an intriguing project idea. However, I've hit a roadblock that's impeding my progress. Every t ...

Having trouble locating the componentwillunmountafterInteraction in the React Native deck swiper

I've been utilizing react native deckSwiper in my project, but I'm having trouble unmounting it from the screen due to an error that says "ReferenceError: Can't find variable componentWillUnmountAfterInteractions". The error stack trace is s ...

Identifying when two separate browser windows are both open on the same website

Is it possible to detect when a user has my website open in one tab, then opens it in another tab? If so, I want to show a warning on the newly opened tab. Currently, I am implementing a solution where I send a "keep alive" ajax call every second to the s ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

Encountering a "product is not a constructor" error when conducting API testing in Postman

Currently, I am developing a REST API using Node.js, Express, and MongoDB with the help of Mongoose. The testing phase is being done using Postman. However, when I make a POST request to the products endpoint, I encounter an error message stating "Product ...

"Error: Unable to access the property '$emit' of an undefined value" - VueJS

I'm currently working on implementing a basic authentication system in vuejs. I have a set of objects containing valid usernames and passwords. I am looping through this list to validate the entered username and password. If there is a match, I trigge ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...

Restarting the timer in JavaScript

How can I reset the countdown timer every time a user types into an input field? I tried using clearTimeout but it doesn't seem to work. Can anyone help me with my existing code instead of providing new code? DEMO: http://jsfiddle.net/qySNq/ Html: ...