Optimal Strategies for Mapping Out Your Travel Plan

I've been working on setting up routes for my backend and I've encountered two different approaches. I'm curious to know which one aligns better with best practices, or if neither is ideal. Despite the minor differences between them, I am eager to determine if there is an objective "best" choice.

Let's take a look at both alternatives:

const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');

router.get('/', flashcardController.readFlashcard);
router.post('/', flashcardController.createFlashcard);
router.patch('/', flashcardController.updateFlashcard);
router.delete('/', flashcardController.deleteFlashcard);

module.exports = router

VS

const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');


module.exports = (app) => {
    router.get('/api/flashcard', flashcardController.readFlashcard);
    router.post('/api/flashcard', flashcardController.createFlashcard);
    router.patch('/api/flashcard', flashcardController.updateFlashcard);
    router.delete('/api/flashcard', flashcardController.deleteFlashcard);

    app.use('/', router);
};

Obviously, the implementation in my app.js file (entry-point for my backend) will need to vary slightly for each of these options.

Answer №1

If you think a router's job is just to handle incoming requests and it's up to the calling code to specify the path where the router should operate, then only the first option allows that flexibility. This way, the caller can use the routes in any desired path.

However, if you prefer the module implementing the routes to be self-sufficient and define the paths where the routes should be installed, then the second option is more suitable.

In my opinion, the more common and versatile approach is the first one where the caller determines the path for the routes. But feel free to choose whichever method suits your needs.

The second option may not be as efficient in its implementation and could be optimized. In fact, having a router might not even be necessary as the routes can be directly installed on the app object without repeating /api/flashcard multiple times.

For instance, the second option could be simplified like this:

const controller = require('../controllers/flashcardController');

module.exports = (app) => {
    app.route('/api/flashcard')
        .get(controller.readFlashcard)
        .post(controller.createFlashcard)
        .patch(controller.updateFlashcard)
        .delete(controller.deleteFlashcard);
};

And, the first option could also be streamlined as follows:

const router = require("express").Router();
const controller = require('../controllers/flashcardController');

router.route('/')
  .get(controller.readFlashcard)
  .post(controller.createFlashcard)
  .patch(controller.updateFlashcard)
  .delete(controller.deleteFlashcard);

module.exports = router

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

Dynamic property access using optional chaining in JavaScript

My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid. export const theme = { headers: { h1: { }, h6: { color: '#828286' }, }, } console.in ...

Is there a method for the Express proxy to always retain the original URL in every situation?

I'm currently utilizing Express Gateway to obtain SSL links for a web-based application. Whenever the gateway receives a URL, it cleans it up by eliminating any double slashes and other unnecessary characters. For example, https://server:port/aaaa/b ...

When integrating express with vue-router, I am encountering an issue with the '#' symbol in my URL

The URL is displayed as localhost:3000/index#/dashboard rather than localhost:3000/index/#/dashboard It seems a bit strange. Below is my express code snippet. app.get('/index', function (req, res) { const html = fs.readFileSync(&a ...

How can I utilize JavaScript on the server-side similar to embedding it within HTML like PHP?

One aspect of PHP that I find both intriguing and frustrating is its ability to be embedded within HTML code. It offers the advantage of being able to visualize the flow of my code, but it can also result in messy and convoluted code that is challenging to ...

Is it acceptable for requests to be handled by asynchronous functions?

My HTTP requests primarily involve asynchronous database operations, so they typically follow this structure: myRouter.post('/groups', (req, res, next) => { groupsController.createGroup(req, res).catch(next); }) Within the controller, I aw ...

Issue with Updating Selected Value in Dropdown List (SemanticUI)

For my dropdown list, I am utilizing SemanticUI <div class="ui dropdown"> <input type="hidden" name="gender"> <i class="dropdown icon"></i> <div class="default text">Gender</div> <div class="menu"> < ...

Implementing React Table selected rows from the parent component

I am currently facing an issue with my React Table component that has selectable rows. Although row selection is functioning properly and the parent component has access to information about the selected rows, I am struggling to set the selected rows from ...

When working with MongoDB, it is important to manage your open connections efficiently. Having more than 5 open

Exploring new technologies like nodejs and mongodb can be exciting, especially when diving into a project. However, upon establishing the db connection, it's surprising to discover the number of database connections that code actually creates. Take th ...

Ways to retrieve POST data in express js

When accessing a website in the browser, I use: xmlHttp.open("POST", "/", true); // true for asynchronous xmlHttp.send("data"); on the client side browser. For node js application, I'm using: app.post("/" ...

Hidden warning to React-select for being uncontrolled

I've integrated react-select into my code: import React, {Component} from 'react'; import Select, {createFilter} from 'react-select'; let _ = require('underscore') class Test extends Component { constructor(props) ...

Ways to swap out a React component for a different one after modifying its state

I'm relatively new to React and I am currently working on a project where I need to display a large image that takes 3-4 seconds to load. To enhance user experience, I plan to implement a loader using the ReactImage component available at https://www. ...

Issue with cookie deletion persists even after using remove('cookie_name') and removeAll() functions in ngx-cookie framework

Having trouble deleting a cookie using ngx-cookie. This is how I am setting the cookie: setCookie(cookie: string) { this.cookieService.put('userDetails', JSON.stringify(cookie), { domain: 'localhost' }); } Even after trying remove(), ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

What is the alternative for watchEffect in VueJS 2?

Once my VueJS 2 component loads, I fill a props variable with data. Here's how it's done: created() { this.events = null Service.getEvents() .then(response => { this.events = response.data }) .catch(error =& ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...

Troubleshooting jQuery: Unable to refresh the webpage

I have a PHP page that contains a form, checkboxes, and a submit button. I added an if statement to execute a PHP script I created when the button is clicked, which deletes certain values from the selected rows. The button functions properly and changes s ...

ways to utilize inline styling in react using javascript

When repurposing an array of React components, I am looking to modify the inline styles generated with them. How can I access and log the inline styles of a React component? UPDATE: see the code snippet below: const pieces = this.props.pieces.map((decl, ...

Navigating with router.push in Vue.js to the same path but with different query parameters

The existing URL is /?type=1 I am attempting to implement router.push on this specific page. this.$router.push('/?type=2'); However, it results in a NavigationDuplicated error. I prefer not to utilize parameters such as /:type ...

Explain the utilization of JSON.stringify in enhancing the efficiency of the memoize function

_ .cacheValues = function(func) { var hash = {}; return function() { var arg = JSON.stringify(arguments); if (hash[arg] === undefined) { hash[arg] = func.apply(this, arguments); } return hash[arg]; }; }; Greeti ...

Discover the steps to implement a live user list in a chat application with the help of angular.js, socket.io, and node

Currently, I am in the process of developing a chat application with AngularJS and Socket.io. The current status of my project allows users to send and receive messages from different individuals. To gain access to the chatbox, users need to input their na ...