What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code:

 const express = require('express');
    const app = express();
    app.listen(5000, function(){
        console.log("server started on port 5000");
    })

    app.get("/", function(req, res){
        res.send("Hi There! Welcome!")
    })

    app.get("/speak/:animalName", function(req,res){
        var animalName = req.params.animalName;
        var sound = "sound";
        if (animalName === "pig"){
            sound = "oink"
        } else if (animalName === "dog"){
            sound = "bau"
        } else if (animalName === "cat"){
            sound = "Miao"
        }

        console.log(req.params);
        res.send("THE " + animalName + " says " + sound);
    })

    app.get("*", function (req, res){
        res.send("Sorry, the page cannot be found")
    })

Upon running the server with Nodemon, everything seems to work correctly. However, when entering a specific pattern in the URL field, although the console.log displays the req.params correctly (for instance, typing "cat" returns { animalName: 'cat' }), the response in the browser is not as expected:

https://i.sstatic.net/rNy1q.png

Answer №1

Make sure to use == or === instead of a single = in your conditions. Using a single equals sign will assign the variable, whereas using double or triple equals signs will test for equality.

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

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Implementing new updates to an object without affecting existing values in Vue.js 2

I am currently facing an issue with updating values for an object received in a payload before saving it to the database. Despite making changes, the new values are not being persisted correctly. I am utilizing Vue.js 2 for this task. How can I effectively ...

Re-activate external script following a language update in Next.js

In my Next.js 13 app, I have implemented a live chat support button that is dynamically added based on the language selection. The code for rendering the button looks like this: import Script from 'next/script'; ... <div id={`onlinehelp-button ...

Formik causing malfunction in MUI DatePicker functionality

In my React project, I am using Formik to manage form processing and MUI UI components for the user interface. While I can select the day and month, I'm experiencing an issue with the year part not updating. Even when I manually type in a year in the ...

Retrieve the information from the API and populate the tables with the data

I'm currently working on fetching API data and displaying it in tables, using mock data for now. Successfully implemented actions and reducers. Managed to call the API but encountered an issue with network calls where I see a blocked response content ...

Locate and retrieve a document by its unique identifier in MongoDB, and then store its information in an array

I am working with two models: Meal and Ingredient. Let's take a look at their schemas: const mealSchema = new Schema({ title: { type: String, required: true }, image: { type: String, required: false }, ingredients: [{ ingredient: { ...

Transforming Javascript code using regular expressions into C#

Currently, I am facing a challenge while trying to translate some Javascript code into .NET. Despite my efforts, I have not been able to get it right. The task at hand involves converting paths like /test/:value1/:value2 in Express for NodeJS to a regular ...

What are some solutions for dealing with NodeJS heap memory errors?

I am currently working with a NodeJS connected database that is 723.1 MB in size, and I am running into memory size issues. To make my database available as an API for use in my VueJS application, I have successfully rendered all the necessary data from a ...

Establish the environment variable for the NPM build process

When utilizing the terminal on my development machine, I am able to execute the following... SOME_VARIABLE=http://localhost:3000/ npm start ... and access the value of SOME_VARIABLE within the code using... process.env.SOME_VARIABLE My question arises ...

Is the Bootstrap Carousel not automatically scrolling when navigating back in Angular?

Whenever I launch my Angular application, the image slider implemented using Bootstrap carousel functions properly. However, upon navigating to another view and returning to the image slider, it no longer auto-slides. Even though I can manually navigate th ...

Issue with Bootstrap Table Style When Using window.print();

The color of my Bootstrap table style is not displaying correctly in the print preview using window.print(). Here is a screenshot showing that the table style is not working properly: https://i.stack.imgur.com/eyxjl.jpg Below is the code I am using: < ...

Why is it that the reduce function is not returning the object I expected?

[['id', '1111'], ['name', 'aaaaa']] I came across this list. { id: '1111', name: 'aaaa' } Now, I would like to transform the list into a different format. My attempt to convert the list into t ...

Step-by-step guide on formatting a route that returns a user based on their username

Here is the Angular API call I am working with: $http({ method: 'POST', url: "http://groep6api.herokuapp.com/user", headers: {'Content-Type': 'application/x-www-form-urlencoded' ...

Issue with Google Charts where the label does not show outside of the bar if the bar is too small

I am encountering an issue with my Google Bar Chart where the bar label is not displaying outside of the bar when it is too large to fit inside. This behavior should be the default, but my charts are not working as expected. The problem can be seen in rows ...

The icon in Material UI button is missing from the display

The button is functional, but the icon inside it isn't displaying correctly:https://i.sstatic.net/MXhIH.jpg Here is the code for the button: <Button color="secondary" aria-label="add an alarm"> <AlarmIcon></AlarmI ...

I am facing an issue where my Popover functions correctly when elements are added using HTML, but not when they are dynamically created

I'm currently working on a method to incorporate multiple popovers that have a similar appearance to the following: The screenshot of my first JsFiddle project (click to view) The initial progress I've made can be seen in my first JsFiddle, acc ...

Switch up div containers with JavaScript based on the set array order of elements?

As I work on creating a list that calculates the sum of selected numbers, I encountered an issue with rearranging the items. Despite successful functionalities like adding images with names, changing languages, and performing calculations, the page keeps r ...

Tips for notifying the user about incorrect login credentials in Ionic 3

I'm attempting to implement a notification system using showAlert to inform users when they enter an incorrect email or password, but I'm having difficulty achieving this using try and catch statements Would it be feasible for me to use try and ...

How about using AngularJS with JavaScript modules?

I have an old AngularJS app (using version 1.2) and I am trying to organize my code into JavaScript modules. However, I am struggling to figure out how to define the controller as a function within the module. In other words, I want to transition from: & ...

Anticipated semicolon in the JavaScript file

I recently came across the dialogflow demo as a reference. However, I encountered an error stating 'semicolon expected' at the method sendTextMessageToDialogFlow. How can I resolve this issue? Below is the code snippet: router.post('/dialo ...