What was the reason for node js not functioning properly on identical paths?

When the search route is placed at the top, everything works fine. However, when it is placed at the end, the route that takes ID as a parameter keeps getting called repeatedly in Node. Why does this happen and how can it be resolved?

router.get('/search', function (req, res) {

    var p_Where = {};

    if (req.query.IsDeleted)
        p_Where.IsDeleted = req.query.IsDeleted;

    if (req.query.CustomerName)
        p_Where.CustomerName = { $like: '%' + req.query.CustomerName + '%' };

    if (req.query.PhoneNumber)
        p_Where.PhoneNumber = { $like: '%' + req.query.PhoneNumber + '%' };

    if (req.query.OmitCustomerID)
        p_Where.CustomerID = { $ne: req.query.OmitCustomerID };

    if (req.query.CustomerID)
        p_Where.CustomerID = req.query.CustomerID;

    if (req.query.ShowAutoGenerated)
        p_Where.IsAutoGenerated = req.query.ShowAutoGenerated;

    if (req.query.DeviceNumber)
        p_Where.DeviceNumber = req.query.DeviceNumber;

    if (req.query.CarrierID)
        p_Where.CarrierID = req.query.CarrierID;

    console.log(p_Where);
    models.Product.findAll ({
        where : p_Where,
    }).then(function (customer) {
        res.json({
            status : true,
            message : "Products has been found",
            data : customer
        });
    });
});




router.get ('/', function (req, res) {

    models.Product.findAll ({
        where: {
            WholeSaleCustomerId: req.get ("wscId")
        },
        include: [models.ProductSpecification]
    }).then (function (Product) {

        if (Product.length == 0) {
            res.status (404).json ({
                status: false,
                message: "No product has been found."
            });
        }else{
            res.json ({
                status: true,
                message: "Products has been found.",
                data: Product
            });
        }

    });

});



router.get (':productId', function (req, res) {
    models.Product.findOne({
        where: {
            WholeSaleCustomerId: req.get ("wscId"),
            id: req.params.productId
        },
        include: [models.ProductSpecification]
    }).then (function (Product) {
        if (!Product) {
            res.status (404).json ({
                status : false,
                message : "No product has been found."
            });
            return;
        }else{
            res.json ({
                status : true,
                message : "Product has been found.",
                data : Product
            });
        }

    });
});

Answer №1

It's all about the order in which routes are checked. The /search route takes precedence over /:productId. This means that when a request is made, the first matching route will be used.

To solve this issue, simply make sure to declare the /search route before the /:productId route in your code. While there may be other ways to work around this problem, they typically involve hacky solutions.

Answer №2

The issue arises when Node identifies the initial matching route as /, causing it to match all subsequent routes. It is recommended to provide more descriptive names for your routes such as /all and /productById/:id

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

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

retrieve data types from an array of object values

I am looking to extract types from an array of objects. const names = [ { name: 'Bob' }, { name: 'Jane' }, { name: 'John' }, { name: 'Mike' }, ] The desired result should resemble thi ...

How to apply class binding within a v-for loop in Vue.js

When using Vuejs3, I am currently iterating through an array of objects: <div v-for="ligne in lignes" :key="ligne.id" :class="{ 'border-b-2':isSelected }" :id="`ligne_${ligne.id}`" > ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

What are the steps to troubleshoot and fix the Internal Server Error on Next.Js?

I recently set up a new Next.js app using the command npx create-next-app. After that, I added Sass to my project with yarn add sass and proceeded to run it with yarn dev. To my surprise, I encountered multiple errors in both my terminal and on localhost. ...

Develop a straightforward static webpage and set it up by installing and launching it using NPM

I am attempting to craft a straightforward HTML page that incorporates CSS/JS and utilizes npm. The objective is to construct a basic page that can be accessed by simply using "npm install" and "npm start". As an example, I will design a page with HTML, ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

Unique calculation for rotational movement

I am currently developing a unique compass application. Although the project is progressing well, I am facing a significant challenge with one aspect: My code calculates degree angles within the range of -360 and 360: -318°, -29°, 223°, -163°, ... ...

Updated the object in an array retrieved from an API by adding a new key-value pair. Attempted to toggle the key value afterwards, only to find that

Essentially, I am retrieving products from an API and including a new key value isAdded in the object within the products array. I utilized a foreach loop to add that key and it was successfully added. Now, when I click the Add to cart button, the product ...

Explore the differences between user input and JavaScript

There seems to be an issue with the second output result. var compareNumber = 3; // Code will be tested with: 3, 8, 42 var userNumber = '3'; // Code will be tested with: '3' 8, 'Hi' /* Enter your answer here*/ if (userNum ...

Encountered an error while running the `npx-create-react-app my-app` command in

When attempting to run 'npx create-react-app my-app', the following error message is displayed: 'npx' is not recognized as the name of a cmdlet, function, script file, or operable program. Double check the spelling and path included to ...

Having difficulty locating the index of the column labeled `Clients` within a table; the result being -1

Having some trouble locating the index of the column name Customers within a table using jQuery/javascript. No matter what I try, it always returns -1 let tableDatacy = "Results_Table"; let columnName = "Customer"; let tableHeaders = [] ...

What could be causing my React component to only render after pressing ctrl + shift + R?

I am facing an issue with my chrome extension where it only appears after refreshing the page using ctrl + shift + r. However, there is a new problem that arises when I click on a link that refreshes the page, causing the extension to disappear and requiri ...

No action is triggered after submitting AJAX data in a WordPress environment

I'm currently working on developing a WordPress plugin that requires querying the database. However, I am facing challenges in getting it to function properly. Here is the code snippet that I have attempted: jQuery('#demo_ajax').submit(func ...

Is there a way to program custom key assignments for my calculator using JavaScript?

As a beginner in the world of coding and JavaScript, I decided to challenge myself by creating a calculator. It's been going smoothly up until this point: My inquiry is centered around incorporating keys into my calculator functionality. Currently, th ...

Alternative image loading in a figure element

I'm currently in the process of putting together an image gallery using Angular 4.3.0, where images are displayed as background images within figure elements rather than img tags. The images are initially resized to smaller dimensions before being use ...

Choose from the Angular enum options

I am working with an enum called LogLevel that looks like this: export enum LogLevel { DEBUG = 'DEBUG', INFO = 'INFO', WARNING = 'WARNING', ERROR = 'ERROR' } My goal is to create a dropdown select el ...

example of using relative jquery countdown.js

I've been attempting to grasp JavaScript and incorporate the countdown found at this link (specifically, the example with a 300-second countdown), but after spending a few hours on it, I haven't been able to get it functioning properly. I have c ...

Address the snack bar problem

In my quest to create a custom snackbar, I have encountered a minor issue with setting and deleting session variables in Node.js. While using global or local variables works well for accessing data on the client side, there is a chance of issues when multi ...

Simultaneously activate the top and bottom stacked components by clicking on them

One of my components has two child components, A and B. Component A is set to position: absolute and placed on top of component B like an overlay. Additionally, component A has a higher z-index. Both components have onClick events attached to them. My que ...