Create pathways for direct access

I've been studying some code written by someone else to improve my understanding. The way they are setting up routes seems a bit unclear to me.

app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist')))

// mount routes
app.use('/', userRoutes)
app.use('/', authRoutes)
app.use('/', postRoutes)

What's confusing me is the use of '/' and app.use instead of app.get(). Normally I would specify the route explicitly rather than using '/' everywhere. Can you explain how this works? Is this considered better practice?

The repository in question can be found at https://github.com/shamahoque/mern-social/tree/master/server

Answer №1

When it comes to writing routes directly, it can quickly become overwhelming and difficult to manage, especially as the number of routes grows. This is where the MVC pattern comes into play, dividing the application into modules or logical blocks based on their specific functionalities. For instance, in a hypothetical hospital management system, you might have modules for authentication, billing, payroll, medical stock, patients, and more. In an MVC setup, it's common practice to have a separate controller for each module. Express offers middleware functionality, also known as Routers, to connect these controllers to their respective API routes (think of it as a roadmap linking routes to controllers).

Once you've defined routes for each module using middleware, you can utilize these routes within your application. These routes handle incoming requests and pass parameters to the appropriate controller for processing. Learn more about Middleware and Routers here: https://www.tutorialspoint.com/expressjs/expressjs_routing.htm

From a code quality perspective, breaking down the code into modular components and using routers to establish connections between them makes it easier for others to understand. It also offers a clearer overview of the application structure, making it simpler to add new modules or functionalities.

For further insights on building a production-ready express app, check out: https://www.freecodecamp.org/news/how-to-write-a-production-ready-node-and-express-app-f214f0b17d8c/

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

Using style binding and ngStyle doesn't appear to be effective for setting a background image within a DIV element in Angular5

After facing difficulties in customizing the spacing of Angular material cards, I decided to create my own cards. However, during this process, I encountered an issue where I needed to set an image as a background inside a div. Despite trying various CSS ...

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

Retrieve JSON data within a service and provide it to a component

I am currently facing an issue with loading data from a JSON file into my component using a service. The data is successfully loaded in the service, as confirmed by the console log; however, when trying to access the data in the component, it does not disp ...

Is there a way to repurpose a JavaScript object that gets sent back to the client upon page loading?

Upon initial page load, an AJAX request fetches a list of JavaScript objects which display only one value each. The page includes buttons to expand each item and reveal the remaining values. Originally, I used another AJAX call to retrieve individual objec ...

Node.js - CSRF Protection Token Undefined

I've been facing challenges with setting up CSRF token generation, and I seem to be missing something. server.js: // configuration ====================================================================== var express = require('express'); va ...

Waiting for a Node.js/JavaScript module to finish running before proceeding

I've developed an express.js application that integrates with MongoDB using mongoose. Currently, I have the mongoose connection code stored in a separate file since it's used across multiple modules frequently. Below is the connector code: con ...

AngularJS checkbox validation requires a minimum of two checkboxes to be selected

When using AngularJS, I am looking to create a validation rule where a minimum of 2 checkboxes must be checked for the input to be considered valid. Here is what I have attempted: <div ng-repeat="item in items"> <label><input type="chec ...

The resource being requested is missing the 'Access-Control-Allow-Origin' header - Issue with Pinterest OAuth implementation

While working on implementing OAuth for Pinterest, I successfully retrieved the access code. However, when attempting to perform a GET /v1/me/ request, I encountered an error in the Chrome console: XMLHttpRequest cannot load . No 'Access-Contro ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...

Having numerous bxsliders implemented in a Genesis child theme

I'm currently working on incorporating multiple bxsliders through custom fields in a wp genesis child theme. The initial slider was successfully implemented using the following function within the genesis child theme functions: add_action('genes ...

You can use jQuery AJAX to submit two forms' data simultaneously in just one submission

I am looking to submit two sets of form data with just one click. <form id="form1"> <input type="text" name="name"> <input type="submit" value="Submit"> </form> <form id=&quo ...

Encountering an error when integrating my library with MUI

Currently, I am working on developing a library that wraps MUI. One of the components I created is a Button, and here is the code snippet for it: import React, { ReactNode } from 'react' import Button from '@mui/material/Button'; impor ...

Exploring smooth scrolling functionality using AngularJS and integrating it with IFrames

After implementing an angular controller, I included the following code: angular.element(document).ready(function () { ... } Within this setup, I added a function to enable smooth scrolling to the hash of window.location.hash using .animate({scrollTop... ...

The latest entries are not visible on Mongoose unless the page is refreshed

There is a router with handlers for GET and POST requests related to documents. When creating new documents and posting them, the redirection works smoothly. However, upon initial page load after creation, only existing documents are displayed. It's o ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

Express - segregated public directory designed for authenticated/unauthenticated individuals

I have a project built with express.js and I'm looking to split the application into two main sections: One for users who are not logged in (with routes only to / - landing page, /login and /* - error404) The second section will be for authorized us ...

Presentation: Troubleshooting Ineffective CSS3 Transitions

I have created a basic slideshow that can accommodate multiple images. Clicking on an image should move to the next slide, and once the last image is clicked, it should loop back to the first slide. The functionality of transitioning between slides seems ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

Tips for preventing redundant AJAX calls following a setTimeout

I have a text field where I check the database for matches when users type. However, I want to avoid overloading the database with unnecessary queries if someone quickly types several characters. After browsing the internet, it seems like the recommended ...