What is the reason for node executing both of these handlers on the server?

My node app is set up with two handlers, one for requests to the root URL and another for the slug. However, when I visit the root or slug URLs, the app crashes and I receive this error:

url is pointing to root
url has a slug
throw err; // Rethrow non-MySQL errors

I'm not sure what I did wrong. Here's my code:


app.get(
    '/:slug',
    (req, res) => {
        connection.query(`select * from blogs where slug="${slug}"`,
            (error, results) => {
                if (error) console.log(error);
                console.log('url has a slug');
                res.render(
                    'somepage',
                     results
                )
            }
        )

    }
)

app.get(
    '/',
    (req, res) => {
        connection.query(`select * from blogs`,
            (error, results) => {
                if (error) console.log(error);
                console.log('url is pointing to root');
                res.render(
                    'index',
                    {
                        title: 'Home page',
                        blogs: results
                    }
                )
            }
        )

    }
)

Answer №1

One potential reason for the issue you are seeing:

Once the homepage is loaded using GET /, browsers also send a request for GET /favicon.ico in order to fetch the icon displayed on the browser tab (such as the one used on StackOverflow found at https://i.stack.imgur.com/ZyKYw.png). This additional request would be handled by your "slug route", with req.params.slug = "favicon.ico". It is likely that the variable slug in your code is not defined. As a result, the select statement may encounter issues during this extra request.

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

bringing in a js file with an import statement at the beginning

I am looking to import a file that brings in another file for use across multiple pages Here is my folder structure: js modules momentum-scrolling index.js about.js contact.js Contents of momentum-scrolling.js: import LocomotiveScroll from &a ...

Tips for scaling and compressing a canvas image using only pure javascript and HTML5 techniques

I am currently working on resizing and rotating a camera picture on the client side without using any special libraries. I have successfully completed most of the task, but I encounter an offset of 320 pixels when rotating the image. The source of this off ...

What is the most effective method for searching a database for latitudes and longitudes that are close

Is there a way to efficiently query a database for documents within range of a specific latitude/longitude pair without having to calculate the distance for every entry in the database? I currently have a set of latitudes and longitudes stored and need to ...

Looking to update a specific element in an array on an hourly basis?

var temperature = [-18 , -18.1 , -18.2, -18.3, -18.4, -18.5, -18.6, -18.7,-18.8, -18.9, -19 , -19.1 , -19.2, -19.3, -19.4, -19.5, -19.6, -19.7,-19.8, -19.9, -20]; $(".warlotemp").html(temperature[0]); $(".warlotemp").append(" C"); I am intere ...

Retrieving cached data using $http in AngularJS

When making a request to an API using $http in AngularJS, I am receiving cached results. Below is the AngularJS code snippet: $scope.validate = function(){ var encodedUserNameAndPassword = Base64.encode($scope.username + ':' + $scope.passwo ...

What is the best way to securely transfer API keys to a React frontend for use in a React component?

I'm currently working with @react-google-maps/api to develop a map component in React. To load the component, we have to provide an API key for useJsApiLoader. How can I securely manage the API key so it's not exposed on the frontend? (Using an E ...

The show more/show less link for a long jQuery paragraph is malfunctioning

I encountered an issue while coding where the "read more" link works correctly, but the "show less" link does not. Despite my efforts, I cannot seem to identify the error. Within this code snippet, there is an anchor tag with class="show-less" that I am u ...

Is there a way to refresh a MongoDB database automatically without relying on requests?

Is there a way to automatically refresh the MongoDB database without relying on user requests in order to ensure maintainable database requests and API calls that do not exceed any limits? My tech stack includes Node, Express, Vue, and Mongo. What concept ...

Why are certain items excluded from comparison within a sorting algorithm?

In a scenario where an array of strings needs to be sorted based on multiple criteria, such as copying a list of directory paths, consistency in the result is crucial regardless of the initial order of the input. The following requirements need to be met: ...

Eliminate JavaScript that blocks rendering:

Currently, I am working on optimizing my website's speed and aiming for a perfect 100/100 score on PageSpeed Insights. The website in question is www.chrispdesign.com. Despite my efforts to relocate the code and make necessary adjustments, I have bee ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

Preserve user-inputted text from jQuery within a div container

With the help of the knowledgeable individuals here, I successfully created a prototype to address an issue I had encountered. The problem involved using a textbox input with a password requirement to update an HTML element. Although everything is functio ...

Guide on using jQuery to automatically scroll to the HTML container related to a clicked letter

I am in the process of finalizing my wiki page and I wish to add a specific function. My goal is that when a user clicks on a letter in the alphabet bar, the browser will smoothly scroll to the corresponding letter within the wiki column. However, I am en ...

Create a duplicate of the table and remove specific rows

Hi there, I have a query about duplicating a table. I am looking to extract specific results and display only those results. To illustrate, here is an example in HTML code: <table class="table table-striped" id="ProfileList2"> <tbody> ...

Managing dynamic backend ports while using axios in React.js- a comprehensive guide!

This morning, I successfully deployed a login app using the MERN stack on Heroku. However, when attempting to log in GET http://localhost:5000/user/login/email/password net::ERR_CONNECTION_REFUSED appeared in the console. I realized that the error w ...

What causes the stack to be undefined following the invocation of new Error()?

Currently, as I'm working on a project using Node.js and Express, I've encountered an issue where errors are not displaying the expected stack trace in the .stack property when viewed through the WATCH window in VSCode. Surprisingly, my error obj ...

Utilizing ES6 Map type in TypeScript for Angular 2 Response Data Transfer Object Definition

Is it possible to utilize the es6 Map type in an HTTP Response DTO? Let's consider an Angular 2 request: public loadFoos(): Observable<FoosWrapper> { return this.http.get("/api/foo") .map(res => res.json()); } Now, take a loo ...

Implement authentication verification on all child endpoints within an express router

I have an express router set up and I want only authorized users to access its routes. I am currently using passport middleware. Instead of adding a check for req.user in every endpoint, is there a more efficient way to handle this? router.get("/", asyn ...

Error encountered while trying to retrieve the response

Currently, I am in the process of developing a script that utilizes node.js, fbgraph API, and the express framework. My task involves sending the user's access_token from an index.html page to the nodejs server via a POST request. I have successfully ...