How to choose between GET/POST and USE in ExpressJS for URL filtering

router.get('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl)

})

VS

router.use('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl)

})

Could someone shed light on the behavior differences between USE and GET methods in Express router? When I use USE, the middleware function runs when I put a URL after '/', however, with GET it doesn't work. How does filtering vary in these cases?

Answer №1

  1. To make sure the middleware is executed solely for GET requests to the / path, you can utilize router.get('/').
  2. If you want the middleware to be triggered by any HTTP method(GET, POST, PUT, etc.) on the / path and its sub-paths(/, /jhds, /jhsd, etc.), you should employ router.use('/').

In essence, use is more versatile as it will match any method and any path that begins with the specified path. On the other hand, get is only designed for handling GET requests and will only match the exact specified path.

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

"Error: The 'operations' multipart field is not found when using graphql-upload and apollo-server

Hey there! I'm currently working on uploading a file using graphql, and here's the code snippet I have: index.js const express = require('express'); const { ApolloServer, gql } = require('apollo-server-express'); const { grap ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Making a Request on Behalf of a Component in Vue.js Using Interceptors

Within my Vue application, I've implemented a response interceptor: axios.interceptors.response.use(function (config) { return config; }, error => { if (error.response.status !== 401) { return new Promise((resolve, ...

Opting for fetch over jQuery's ajax for making successful GET requests to an API

Recently, I found myself in a situation where I needed to convert a function that uses a remote API from returning a callback to returning a Promise. This change presented an opportunity for me to also switch from using $.ajax to fetch, since fetch already ...

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

Utilizing JavaScript to showcase information retrieved from the database

After implementing this code example for a cascaded drop-down menu, I would like to incorporate the names of individuals residing in a specific city. How can I achieve this functionality once a city is selected? Demo link: Complete code snippet below: ...

Why does JSON remain unchanged when a value is explicitly assigned in Javascript

Why isn't my JSON structure updating when I explicitly assign a new value? items[0][i]['human_addressItem'] = address; I am trying to reverse geocode the latitude and longitude to obtain the human address, which is working fine. However, I ...

Which backend framework is most commonly utilized with ReactJS?

Currently, my project consists of: Frontend Frameworks - PHP Codeigniter and PHP Laravel Backend Framework - JAVA Springboot I am considering changing the Frontend Framework to ReactJS. I would like advice on the most popular backend framework to pair w ...

Can an AJAX request continue running even after the user has moved to a different page within the website?

Currently on my website, users are able to submit a form using ajax. The response, indicating whether the form was successfully submitted or if there was an issue, is displayed in an alert message. However, due to the asynchronous nature of this process, i ...

next-auth consistently redirects when encountering errors with credential providers

I've been working on integrating next-auth with my next js app using the Credentials provider. However, I'm facing an issue where every time a login fails, it automatically redirects to the /api/auth/error route. What I actually want is to handle ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

What could be causing the Metamask account address to return as undefined even after it was stored in the useState() function?

A code snippet I have establishes a connection to the Metamask wallet and initializes the account address using useState() hook. const [currentAccount, setCurrentAccount] = useState("") const connectWallet = async () => { try { if (! ...

Show the chosen value from the dropdown menu on all JSP pages

I have a header.jsp file containing a dropdown box labeled "Role". This header.jsp is designed to be included in all other JSP files using a directive. Once a user logs in, they are directed to a homepage where they must select a value from the dropdown ...

What is the best way to handle code versioning using Django, Angular2, and Webpack?

Currently, I am utilizing Django in conjunction with Angular 2 and Webpack. Within Django, I have set up a URL to display my application at http://example.com/user/beta. Initially, my index.html file is rendered, which contains my Angular 2 components. Wit ...

Is it possible to customize the appearance of the selected item in a select box? Can the selected value be displayed differently from the other options?

My current project involves working with the antd' select box. I have been trying to customize the content inside the Option which usually contains regular text by incorporating some JSX into it. The output currently looks like this: I have also crea ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

What techniques can I use to generate a 3D visual effect by shifting the background image layer as the user scrolls (creating a Parallax effect

I have combined two images in the heading; one on top of the other. My goal is to create a subtle vertical movement in the background image as the user scrolls, giving the illusion of depth. Both images share the same width, but the background image is tal ...

Tips on creating a transition in React to showcase fresh HTML content depending on the recent state changes

I am completely new to React and recently completed a project called Random Quote Machine. The main objective was to have a method triggered inside React when the user clicks a button, changing the state value and re-rendering to display a new quote on the ...

What is the best method for displaying the index page in node.js using ejs-templating instead of traditional express.static content?

When using a restaurant food menu generator, I am able to view it with HTML by utilizing the following code: app.get('/', function (req, res) { res.sendFile(__dirname + '/views/index.html'); }); This method uses express static. Bu ...

Error: Unable to access the 'clearAsyncValidators' property as it is undefined when running Jest tests on an Angular component

Encountering an Error While Testing Components with Jest Here is my code block for onClickLogin() method: onClickLogin() { if(this.loginForm.valid) { this.api.getLoginData().subscribe(res => { const user = res.find(a => { ...