Why am I not receiving the expected feedback after submitting a request for a specific parameter in a Node.js and Express Router REST API?

Developed a Node module utilizing the Express router to facilitate the routes for the dishes REST API.

Index.js file:

const express = require('express');
const http = require('http');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const app = express();  // indicating the use of the express node module
const dishRouter = require('./route/dishRouter');
app.use('/dishes/:dishId', dishRouter);

const hostname = 'localhost';
const port = 3000;





app.use(bodyParser.json());  

app.use(morgan('dev')); 

app.use(express.static(__dirname + '/public')); 


app.use((req, res, next) => {
    console.log(req.headers);
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end('<html><body><h1>This is an express server </h1></body></html>');
});

const server = http.createServer(app); 
server.listen(port,hostname,() => {
    console.log(`Server runnig at http://${hostname}:${port}`);
})

DishRouter.js file:

const express = require('express');
const bodyparser = require('body-parser');

const dishRouter = express.Router({mergeParams:true});

dishRouter.use(bodyparser.json());

dishRouter.route('/') 
.all((req,res,next) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    next();
})
.get((req,res,next) => {
    res.end('Will send all the dishes to you!');
})
.post((req,res,next) => {
    res.end("Will add the dish : " + req.body.name + "  with details: " + req.body.description);
})
.put((req,res,next) => {
    res.statusCode = 403;
    res.end('PUT is not supported by /dishes');
})
.delete((req,res,next) => {
    res.end('Deleting all the dishes');
});


dishRouter.route('/:dishId')
.all((req,res,next) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    next();
})
.get((req,res,next) => {
    res.end('Will send the dish ' +req.params.id +' to you!');
})
.post((req,res,next) => {
     res.statusCode = 403;
    res.end('POST operation not supported on /dishes/'+req.params.id);
})
.put((req,res,next) => {
    res.write('Updating the dish: ' + req.params.id + '\n');
    res.end("Will add the dish : " + req.body.name + " with details: " + req.body.description);
})
.delete((req,res,next) => {
    res.end('Deleting the dish '+req.params.id);
});

module.exports = dishRouter ;

The implementation required to support GET, PUT, POST, and DELETE operations on each endpoint. Although the code works correctly for dishes, it presents the same results for dishId as well.

Upon sending a GET request to localhost:3000/dishes/28, the following response is returned:

Will send all the dishes to you!

Answer №1

Express routes are matched on a first come first serve basis. If your root route / is defined first, it will always be used to match any route. To change this behavior, try moving your root route to the bottom of the file.

const express = require('express');
const bodyparser = require('body-parser');

const dishRouter = express.Router({mergeParams:true});

dishRouter.use(bodyparser.json());

// Routes for specific dish 
dishRouter.route('/:dishId')
.all((req,res,next) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    next();
})
.get((req,res,next) => {
    res.end('Will send the dish ' +req.params.id +' to you!');
})
.post((req,res,next) => {
     res.statusCode = 403;
    res.end('POST operation not supported on /dishes/'+req.params.id);
})
.put((req,res,next) => {
    res.write('Updating the dish: ' + req.params.id + '\n');
    res.end("Will add the dish : " + req.body.name + " with details: " + req.body.description);
})
.delete((req,res,next) => {
    res.end('Deleting the dish '+req.params.id);
});

dishRouter.route('/') //mount this express router at the /dishes endpoint.chain all GET PUT POST DELET method already do this router

.all((req,res,next) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    next();
})
.get((req,res,next) => {
    res.end('Will send all the dishes to you!');
})
.post((req,res,next) => {
    res.end("Will add the dish : " + req.body.name + "  with details: " + req.body.description);
})
.put((req,res,next) => {
    res.statusCode = 403;
    res.end('PUT is not supported by /dishes');
})
.delete((req,res,next) => {
    res.end('Deleting all the dishes');
});
module.exports = dishRouter ;

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

I'm having issues with running my npm install -g react-native-cli

Unfortunately, I am unable to run react-native on my mac due to a permission issue. Despite my attempts to rectify this problem and obtain the necessary permissions, I have been unsuccessful. npm WARN checkPermissions Missing write access to /usr/local/ ...

Typescript is unable to locate the .d.ts files

Working on a personal project and came across a library called merge-graphql-schemas. Since the module lacks its own typings, I created a file at src/types/merge-graphql-schemas.d.ts In merge-graphql-schemas.d.ts, I added: declare module "merge-graphql-s ...

The routes may be the same in both React Router Dom v6, but each one leads to a different

I am struggling to set up different routes for navigation and I'm not sure how to do it. Here is what I have attempted so far: const router = createBrowserRouter( createRoutesFromElements( <> <Route path="/" element={<NavB ...

Change the URL structure from ex.com/forum?id=1 to ex.com/#/forum?id=1 in AngularJS

Hey there! I'm in the process of creating a Forum using AngularJS and need some guidance. First things first! I've successfully established a connection to my database with: <?php session_start(); $db = new mysqli("localhost","root",""," ...

Refresh selected items after inserting data via ajax in CodeIgniter

I have a select list on my view that allows users to add new items using a plus button. However, when a new item is added, the list does not refresh. I don't want to refresh the entire page with an ajax query. Instead, I am trying to implement a metho ...

New feature in Safari extension: transferring window object from inject script to global page

Is it possible to transfer the window object from an injected script to a global.html page? I am attempting to pass the window object as part of an object to the global page. However, when I try to dispatch the message from the "load" listener function, i ...

Encountering a "variable not found" error when trying to run the JavaScript code to manipulate the web element

Upon executing the command to change the value of a web element text, I encountered an error stating "Can't find variable: e." sel=webdriver.PhantomJS() sel.get=('http://stackoverflow.com/questions?pagesize=50&sort=newest') elements=sel ...

What is the best approach for resolving this asynchronous task sequencing issue in JavaScript?

Below is a code snippet where tasks are defined as an object and the function definition should ensure the expected output is met. Let tasks = { ‘a’: { job: function(finish){ setTimeout(() => { ...

When using JavaScript with React, setting a value after the onBlur event can result in users having to click

In my React form, I have an input button with an onBlur event that sets the value to a useState property. However, after the onBlur event is triggered, the user has to click the button twice to focus on it properly. It seems like the page needs time to pro ...

What methods can be used to validate try-catch code in JavaScript with Jest, and how can a next() call be incorporated with middleware in

Currently, I am in the process of creating an API and one of my tasks involves testing a try-catch block. My main objective is to ensure that any errors caught by the block are passed through 'next()' in Express to reach the next middleware. To ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

How can you use ng-click to re-sort data that has already been loaded using Angular's ng-click?

I'm having trouble switching between loading and sorting the information in the table using ng-click. The functions to load and sort work correctly individually, but I can't seem to switch between the two. It seems like I reset the countries data ...

HTML5 input type Color displays individual RGB values

This code snippet opens up a variety of options for the user to manipulate different color values such as R, G, B, HEX VALUE, HUE, etc. However, the specific requirement is to only extract the Red value. <input id="color_pick"type="color" value="#ff0 ...

My extension seems to be missing the content script I uploaded

I am currently developing an extension for Google Chrome. My goal is to create a content script that can retrieve meta tags from the tab when the popup is clicked. In my manifest, I have included the following permissions: "content_scripts": [{ "js" ...

Simplest method for implementing a post-retrieval transformation hook in Mongoose

Having recently ventured into the world of Mongoose, I've been tasked with expanding an existing project. While I quickly understood pre and post hooks, I couldn't help but wonder why there aren't similar hooks for find, only for save and de ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...

Starting with NodeJS: Troubleshooting module not found error

I'm new to NodeJS and I'm following the guide on the official NodeJS site to create a server. I have successfully installed NodeJS on my computer and created an app.js file with the code below: const http = require('http'); const host ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

Another option instead of sending back a JavaScript tag in the Ajax response

After making an ajax request in my code, I receive some HTML that contains specific elements requiring custom event handling. For example: <div> <!--some html--> <button id='specialbutton'></button> </div> <scr ...

Listening for dates in NodeJS and triggering callbacks

Is there a method or module available that allows me to monitor the date and trigger a specific action when a certain condition is met without relying on setTimeOut? What I am looking for: if(currentHour==="08:00:00"){ doJob() } EDIT : To clarify, wha ...