Sub-routes in Main route not getting static files ExpressJS

To serve static files in ExpressJS, you can use the express.static middleware. By default, this middleware will serve files from a directory named "public" in the root of your project. However, if you want to serve static files from a sub-route within your main route, you need to follow these steps:

  1. Create a directory to hold your static files: In your main route directory, create a new directory to hold your static files. For example, you can create a directory named "static" within the main route directory.

  2. Move your static files to the new directory: Move all your static files, such as CSS, JavaScript, and images, to the newly created directory.

  3. Import the path module: In your main route file, import the path module using the require function. This module is used to manipulate file paths.

  4. Define the sub-route: In your main route file, define the sub-route where you want to serve the static files. This sub-route should be defined after the main route is created.

  5. Use the express.static middleware for the sub-route: In the sub-route definition, use the express.static middleware to serve the static files from the newly created directory. Pass the path to the directory as an argument to the middleware. To do this, use the path.join method to join the main route directory path with the sub-route directory path.

Here is an example that illustrates these steps:

const express = require('express');
const path = require('path');

const app = express();

// Define main route

// Define sub-route for serving static files
const staticRoute = express.Router();
app.use('/subroute', staticRoute);

// Serve the static files
const staticFilesPath = path.join(__dirname, 'static');
staticRoute.use(express.static(staticFilesPath));

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

In this example, the static files located in the "static" directory within the main route directory will be served when accessing the "/subroute" route. For example, if you have a file named "styles.css" in the "static" directory, it can be accessed at "http://localhost:3000/subroute/styles.css".

This setup allows you to serve static files from a sub-route within your main route in ExpressJS.