Having trouble retrieving an object through a GET request in Node.js with Express

Currently, I am going through a tutorial on Node.js by Traversy Media and I have encountered an issue that has me stumped. The problem arises when I attempt to retrieve the response of a single object from an array of objects using the following code:

app.get('/api/members/:id', (req, res) => {
  res.json(members.filter(member => member.id === parseInt(req.params.id)));
});

However, upon testing this code in Postman or typing it into my browser as

http://localhost:5000/api/members/1
, it returns an empty array instead of the expected result.

This is the content of my main JavaScript file:

const express = require('express');
const path = require('path');
const app = express();
const logger = require('./middleware/logger')

const members = require('./Members')

//init middleware
//app.use(logger);

//Gets all members

app.get('/api/members', (req, res) => res.json(members));

//Get Single Members
app.get('/api/members/:id', (req, res) => {
  res.json(members.filter(member => member.id === parseInt(req.params.id)));
});
//Set a static folder
app.use(express.static(path.join(__dirname, 'public')));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

And here is the contents of the Members.js file:

const members = [
    {
      name:"john",
      email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6cc...@example.com]",
      status: "active"
    },
    {
      name:"sally",
      email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12617...@example.com]",
      status: "inactive"
    },
    {
      name:"josh",
      email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c161...@example.com]",
      status: "active"
    }
];

module.exports = members;

I seem to be at a roadblock with this issue and would greatly appreciate any assistance provided. Thank you.

Answer №1

It seems like the objects in your array lack an 'id' field, causing the filter to not find any matches.

To clarify, you're essentially saying: 'Find the object in this array with an 'id' field of X', where X is req.params.id. However, since your objects only contain 'name', 'email', and 'status' fields but no 'id' field, the filter method is unable to match anything.

You can easily test this out by making a simple adjustment:

Replace the following

app.get('/api/members/:id', (req, res) => {
  res.json(members.filter(member => member.id === parseInt(req.params.id)));
});

With this

app.get('/api/members/:email', (req, res) => {
  res.json(members.filter(member => member.email === req.params.email));
});

Then, when you send the request, use '[email protected]' as the parameter, and you should receive the corresponding record:

http://localhost:5000/api/members/[email protected]

    {
      name:"josh",
      email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e04011d062e030f0702400d0103">[email protected]</a>",
      status: "active"
    }

This behavior is due to the presence of an email field in your objects, allowing for successful matching based on that criteria.

To sum it up, the current code isn't functioning because it's trying to match objects based on an 'id' field that they don't possess.

If you were to modify your data structure as follows:

    {
      id: 1, // Added 'id' field
      name:"josh",
      email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fefbe7fcd4f9f5fdf8baf7fbf9">[email protected]</a>",
      status: "active"
    }

You would then have a specific field to compare against. In this example, if you provided '1' as the id parameter, your code would successfully match that document.

I hope this explanation clarifies things and proves helpful.

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 retrieve DOM value due to Vue.js template being inaccessible in Chromium, including from both DevTools and extensions

Currently, I’m developing a Chrome extension that needs to retrieve specific values from a webpage such as the item title. However, instead of fetching the actual title, it is reading a Vue.js template variable. Even when I use DevTools to inspect the p ...

Encountering a 403 Forbidden error while attempting to access a website built with Next.js

Every time I try to access the Next.JS website that's been deployed on IIS using the HTTP address, I'm faced with this error message: Get http://...../_next/static/chunks/webpack-73760e2208a549db.js net:: ERR_ABORTED 403 (Forbidden) However, w ...

Printing from a Windows computer may sometimes result in a blank page

Looking to incorporate a print button into an HTML page, I'm facing an issue. The majority of the content on the page should not be included in the printed version, so my approach involves hiding everything in print and then showing only the designate ...

Executing a cURL request using Node.js

Looking for assistance in converting the request below: curl -F <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1a777f7e737b275a73777b7d7f34706a7d">[email protected]</a> <url> to an axios request if possible. ...

Incorporating a protected Grafana dashboard into a web application

I am looking to incorporate Grafana into my web application using AngularJS. The main objective is to allow users to access the Grafana UI by clicking on a button within my application. Setting up an apache reverse proxy for Grafana and ensuring proper COR ...

Retrieve request header in Nest.js Passport local strategy

Is there a way to retrieve the request headers in passport local strategy? My objective is to establish a separate database for each entity using mongodb, and I need to determine the subdomain before authentication in order to connect to the correct data ...

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

I am unable to view the metrics and HTTP requests/responses data on the Azure Application Insights dashboard for my Node.js Express application

Currently integrating Azure App Insights into my NodeJS app (specifically a Remix app using Express). However, after setting up the library, I am not able to see any metrics appearing on my Application Insights Dashboard or the "Performance" tab. https:// ...

"Integrating multiple partials with templateUrl in AngularJS: A step-by-step

Is there a way to merge partial views using the templateUrl attribute in an AngularJS directive? Imagine having a directive like this: .directive('combinePartials', function () { var mainPartial = "mainpartial.html", var template2 = "pa ...

HTML5 canvas processing causing web worker to run out of memory

Within the Main thread: The source image array is obtained using the getImageData method. It is represented as a uint8ClampedArray to store the image data. Below is the code executed in a web worker: (This operation generates a high-resolution image, but ...

Using Sequelize to send data from the client-side to the server-side

I am currently developing a project for a fictional library database and website interface. I am facing an issue where only 2 out of the 4 new loan form inputs are being passed to the req.body. Even though all items have a name attribute, it seems like onl ...

Select multiple rows by checking the checkboxes and select a single row by clicking on it in the MUI DataGrid

I am currently utilizing the MUI DataGrid version 4 component. The desired functionalities are as follows: Allow multiple selections from the checkbox in the Data Grid (if the user selects multiple rows using the checkbox). Prevent multiple selections fr ...

``There seems to be a problem with decoding JSON data in Swift, as some information

I am currently working on querying the NASA image API with Swift 4. After testing my network request and decoding setup using JSONPlaceholder, everything was functioning properly. However, when I switched to the NASA API URL and JSON data structure, I enco ...

Alert-Enabled Random Number Generation Tool

I'm struggling to create a program that randomly generates a number between 1 and 20. If the number is less than 10, it should display "fail," and if it's greater than 10, it should display "success." I can't seem to figure out where I went ...

The conversion of string to number is not getting displayed correctly when using console.log or document.write. Additionally, the concatenated display is also not functioning as intended

Being new to JS and HTML, this program was created to enhance my understanding of the concepts. I attempted a basic program to convert a string to a number in three different ways, but I am having trouble determining if the conversion actually took place. ...

What is the best way to include the "onChange" function in a component that does not natively support this prop?

After finding a useful code snippet on this page to switch languages, I attempted to enhance it by incorporating material UI components for better styling. However, whenever I change the language, it redirects me back to the home page because the MenuList ...

Instruction on inserting NativeBase footer into my React Native application?

As someone new to React Native, I am trying to include a footer bar in my app. Below is the code snippet from my dashboard.js file where I attempted to add the footer bar, but it doesn't seem to be working as expected: import React, { memo } from &ap ...

Is there a way to extract a token from the URL in a Nextjs/React application?

I am currently developing a project that relies heavily on API integration. My front-end interface is built using React and Next.js, while the back-end API is developed with Laravel. Within my front-end page, I have implemented a token in the URL to help ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

What are the steps to generating and sharing 'npm create' scripts?

I am looking to develop and release a script on npm that functions similarly to: npm create qwik@latest or yarn create next-app --typescript However, I am unsure where to begin. Despite searching extensively online, I have not been able to find any helpf ...