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

Creating a series of spots arranged in a semi-transparent line using JavaScript for a unique canvas

My attempt at creating a highlighter is encountering issues with transparency The problem might be due to using lineCap=round, resulting in multiple dark spots appearing in a single line (which shouldn't happen). It's difficult to fully describe ...

Locating a record within a database that contains an objectId field linking to a separate collection

I have defined two collections in the following manner const BookSchema = new mongoose.Schema({ title: String, author: { type: mongoose.Object.Types.ObjectId, ref: "author" } }) const BookModel = mongoose.model(" ...

Is there an issue with loading CSS and JavaScript in mobile view on a website built with CodeIgniter?

My experience with codeigniter has been great so far, but I encountered an issue when trying to view my work on different devices. Here is the problem: Web: Broswer View | Browser (Responsive Design View) Mobile: Screenshot 1 | Screenshot 2 _htaccess: ...

Explore by the anchor tag

I've recently implemented a search bar utilizing Bootstrap. This is the code for the search bar: <div class="md-form mt-0"> <input class="form-control" id="myInput" type="text" placeholder="Sear ...

Issues with rendering in Safari have been reported when using node.js and express.js, where res.render displays the HTML source as plain text instead

When I use res.render('mytemplate', data), everything works perfectly in most browsers, except Safari (including iOS). In Safari, instead of rendering the content, it displays plain text and some header information: HTTP/1.1 success unknown X-Po ...

Switching out old files with new files in a directory using NodeJS and Multer

I am working on a project using Node.js and Multer where I need to replace an existing file in a directory with a new one when uploading. My approach is to first read the content of the directory, delete it, and then upload the new file. const express = re ...

What approach does JavaScript take when encountering a value that is undefined?

Having recently delved into JavaScript and exploring a book, I came across an interesting example in the recursive chapter: function findSolution(target) { function find(current, history) { if (current == target) return history; else if (c ...

Adjust the background of the page at regular intervals

I currently have: <script type='text/javascript'> var imageID=0; function changeimage(every_seconds){ //change the image if(!imageID){ document.getByTagName("body").src="icwXI.jpg"; imageID++; } else{if(imageID==1){ document.ge ...

Node-sass installation through NPM causing errors

I'm encountering difficulties installing node-sass in a project that builds and runs perfectly on my computer, but is causing major issues on my Surface when trying to install the packages. Note: I've attempted reinstalling and rebuilding the pr ...

What is a creative way to get rid of old content on a webpage using jQuery without relying on the

As I work on my crossword project, I have almost completed it, but encountering a problem. Within my HTML code, I have a select list that loads a .JSON file using Javascript. <form method="post" id="formulaire"> <div class="toto"> <sel ...

Navigate to the specified location using AJAX

When I update a comment using AJAX, I want to automatically scroll down to the updated comment: $("#aggiorna").click(function(){ var value = $("#id").val(); var dato = $("#comment_edit").val(); var dato1 = $("#user_id").val(); var dato2 = ...

What steps are involved in setting up the landing page for a small express application?

I have a node express server set up with the Webpack Dev Server wrapping it The express app is launched from the main directory where static files are stored in a folder named "public" Here is the configuration line: server.app.use(express.static(__dirn ...

Generating and assigning a unique filename based on a specific string - gulp

Looking for help as a complete beginner in Gulp. I'm trying to use a string from one file to name and create a new file. This way, I can identify the white label deployed on the server. One of the contents in the file with the string is: {"TITLE":"n ...

What is the process for integrating an autoplay script into Turn.Js?

Can someone guide me on how to implement this code in Turn.Js? setInterval(function() { $('#flipbook').turn('next'); }, 1000); ...

Issue encountered during Angular upgrade from version 2 to 4 due to a mismatch in node versions

Encountering an error while trying to run npm start: ERROR in Cannot read property 'getSymbolByModule' of undefined. Checked the node version in cmd using node -v, resulted in V6.11.1, however, when executing ng-v cmd, got: angular-cli: 1.0.0-be ...

Can you effectively leverage a prop interface in React Typescript by combining it with another prop?

Essentially, I am looking to create a dynamic connection between the line injectComponentProps: object and the prop interface of the injectComponent. For example, it is currently set as injectComponentProps: InjectedComponentProps, but I want this associat ...

Unable to install npm package in a directory that is mounted on another location

After brainstorming, my concept involves utilizing a docker container to build JS and CSS assets separately from the main application. I have the code stored on the host machine and am attempting to mount the directory containing my code as a volume to the ...

What is the best way to create a smooth transition for a bootstrap navbar in chrome, toggling from right to left on

I have successfully modified the bootstrap navbar to toggle from right to left instead of top to bottom using the following code: For HTML- <nav class="navbar navbar-inverse" role="navigation" style="height: 55px; padding-top: 2px; background-color: # ...

Ensuring a continuous operation of Node.js on AWS EC2 even after exiting the console

Currently, I am using aws ec2 for hosting a web server with node.js and apache. I find it inconvenient that I have to log in to ec2 through the terminal each time to run npm start. I want to set it up so that it continues running even when I'm not o ...

What is the process for setting up Vue.js and using it in conjunction with Sails JS?

After successfully setting up the backend of my website using Sails JS, I decided to integrate Vue.js into my project. Following the installation of Vue and VueResource through npm install --save, I created an app.js file in my assets/js folder. However, ...