Navigating to JSON input in Express correctly

I have successfully created a basic Express-based API to serve JSON data, but now I want to enhance its functionality. The JSON file follows this structure: (some sections are excluded)

[{
  "ID": "1",
  "NAME": "George Washington",
  "PAGE": "http://en.wikipedia.org/wiki/George_Washington",
  "DATE1": "30/04/1789",
  "DATE2": "4/03/1797",
  "PARTY": "Independent ",
  "IMG": "GeorgeWashington.jpg",
  "THUMB": "thmb_GeorgeWashington.jpg",
  "HOMESTATE": "Virginia"
}

Below is a snippet from my index.js for handling Express routing:

var express = require('express');
var app = express();

app.set('port', process.env.PORT || 3000);

var myData = require('./data.json');

app.get('/api', function(req, res){
res.json(myData);
});

app.get('/api/:id', function(req, res){
  res.json(myData[req.params.id]);
  });

While a call to /api returns the entire dataset and /api/1 fetches the first entry, I aim to create another route that allows users to access specific elements within the JSON. For instance, calling

https//<blah>/api/1/HOMESTATE

should return

"HOMESTATE": "Virginia"

Is it possible to achieve this using parameters or do I need to iterate through the JSON based on the provided ID? Any guidance with code examples would be highly appreciated.

Answer №1

One way to achieve this is by utilizing route parameters.

app.get('/api/:id/:property', function(req, res){
  var response = {};
  response[req.params.property] = myData[req.params.id][req.params.property]
  res.json(response);
});

To enhance the stability of your application, it is recommended to implement error handling to handle invalid route parameters and prevent crashes.

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

Tips for saving the circular slider value to a variable and showcasing it in the console

I have coded a round slider and need assistance with storing the slider value in a variable and displaying it in the console using JavaScript. I want to store the tooltip value in a variable for future use. $("#slider").roundSlider({ radius: 180, min ...

Sending a function along with event and additional arguments to a child component as a prop

I've managed to set up a navigation bar, but now I need to add more complexity to it. Specifically, I have certain links that should only be accessible to users with specific permissions. If a user without the necessary permissions tries to access the ...

Is the Jest function, containing an asynchronous call to User.findAll [using Sequelize with PostgreSQL], failing its test?

Why is my test failing for the getAllUsers function? I suspect that the assertions are executed before all async calls to User.findAll complete. Any suggestions on how to fix this? Here is the code being tested: const { Op } = require('sequelize&apo ...

The problem stemming from the implementation of the useNavigate() Hook in a personalized React-Admin application

I've encountered a complex issue in my React-Admin application. Whenever I attempt to utilize the useNavigate() hook within my custom login component (MyLoginPage), an error message pops up: [Route] is not a <Route> component. All component chi ...

What is the correct way to securely send the username and password from a ReactJS frontend to the backend for authentication?

My React application includes an onChange function on a form that collects username and password. Upon submission, the username and password are sent to the server side using redux dispatch in Node.js. On the server side, I am authenticating the credentia ...

Adding a JSON array to HTML using JavaScript

Looking to incorporate JSON Array data into an HTML list with Headings/Subheadings using JavaScript. I experimented with two methods - one involving jQuery and the other mostly vanilla JS. The initial attempt (link here: http://jsfiddle.net/myu3jwcn/6/) b ...

Node Package Manager (NPM): The main entry point to the heart of the

I am currently in the process of developing a custom NPM package. This package requires a module from the user's application root directory, specifically a properties module that is placed there by the user themselves. My main question is: How can I ...

Is it possible to reset only certain data values in Vue without re-initializing the entire set?

In the development process, we often encounter the need to re-initialize data structures. One common method is as follows: function initialData() { return { is_active: true, is_collapsed: true, resetable_data: 'value' ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

Contrasting app.use() and app.get()

const express = require('express'); const app = express(); const PORT = 3000; // The following middleware stops the request flow app.use(function (req, res, next) { console.log("Middleware has been triggered") next(); }); / ...

What strategies can be implemented to transform a lengthy if-else statement into a more optimized

I have a piece of code where I am setting the status of two scope variables based on an AND operation. Depending on the key, I call the relevant method. The only difference between the two methods is checking prop3. I believe the code is quite redundant ...

converting HTML values to TypeScript

I'm a beginner with Angular and could use some assistance. Currently, I have two components - one for the index and another for navigation. Within the index component, there are subcomponents that change based on the value of a variable called produ ...

What could be causing a react element to fail to update?

I'm currently working on a React component that interacts with a MaterialUi text form. The component utilizes a useState hook to update based on the input received. My goal is to have another variable update when the form is submitted, which will be d ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

The current error message states that the function is undefined, indicating that the Bookshelf.js model function is not being acknowledged

I have implemented a user registration API endpoint using NodeJS, ExpressJS, and Bookshelf.js. However, I encountered an error while POSTing to the register URL related to one of the functions in the User model. Here is the code snippet from routes/index. ...

Address Book on Rails

Hello, I'm relatively new to this and would be grateful for any assistance. My goal is to utilize the data saved by a user in their address book, and then offer them the option to use that address for delivery. Below is my Address controller: class A ...

This TypeScript error occurs when the props are not compatible and cannot be assigned to

Hello fellow Internet dwellers! I am a novice in the world of coding and TypeScript, seeking some assistance here. I am attempting to extract an array of objects from props, transform it into a new object with specific information, and then return it - ho ...

Having difficulty logging in a user due to an E11000 error showing up in the collection for duplicate keys

I'm encountering an issue while registering a user and saving the data in the mongo database. The initial registration works perfectly fine, but subsequent attempts result in the following error: {"message":"E11000 duplicate key error c ...

What is the correct method for executing an API request within a div?

I am currently facing a challenge in displaying data in a table sourced from 2 different tables in my database, connected by foreign keys. To retrieve the list of stores, I use the following code snippet: useEffect(()=>{ axios.get("http://localhos ...

Looking for assistance in streamlining JavaScript for loops?

I am currently working on a project involving a random image generator that displays images across up to 8 rows, with a maximum of 240 images in total. My current approach involves using the same loop structure to output the images repeatedly: var inden ...