Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project stored in my JSON file:

"data": {

    "projects": [
        {
            "id": "0",
            "project_name": " ",
            "description": " ",
            "technologies": [ " "],

        },
        {
            "id": "1",
            "project_name": " ",
            "description": " ",
            "technologies": [ " "],

        },

I am currently working on setting up a route where the URL contains an :id parameter to display content specific to each project's ID. For instance, if I visit http://localhost:8000/project/1, I expect to see details related to project 1. Similarly, by navigating to http://localhost:8000/project/2, information about project 2 should be displayed.

router.get('/project:id', (req, res) => {
res.render('project');
req.app.locals = data.projects.id;
const { id } = req.params //this variable represents the id of the project
const { side } = req.query; //this variable represents the page loaded with each project's info

However, I am facing challenges in implementing the JavaScript logic required to achieve this dynamic content rendering. Any assistance or guidance would be greatly appreciated!

Answer №1

To accomplish this task, implementing a loop is essential:

for (let item of data.projects){
  if(item.id === id){
    res.status(200).json(item);
  } else {
    res.status(500).json({message: "Sorry, there are no projects matching this ID"});
  }
}

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

How to redefine TypeScript module export definitions

I recently installed a plugin that comes with type definitions. declare module 'autobind-decorator' { const autobind: ClassDecorator & MethodDecorator; export default autobind; } However, I realized that the type definition was incorrec ...

What is the best way to ensure that the table header is printed on every page when printing?

My table has a large number of dynamic rows, and when I try to print or preview it using the window.print() function, only the table header (thead) appears on the first page. How can I make sure that the table header appears on each printed page? <div ...

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

The npm script failed to build in Docker without any clear errors

I currently have the following Dockerfile setup: Dockerfile: FROM node:alpine WORKDIR /usr/src/app COPY package*.json ./ COPY src ./ RUN npm --verbose install RUN npm run build EXPOSE 8000 These are the dependencies listed in packages.json "dependen ...

Modifying the value property of the parent element

Here is an example of the HTML code I am working with: <td value='3' style='text-align: center'> <select class='selection' onchange=''> <option value='1'>1</option> <opti ...

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

Is it possible to send a message from a child iframe to its parent using HTML5 cross-browser compatibility

I've been following this tutorial on a video-sharing website, which demonstrates how to securely pass messages between an iframe and its parent. The tutorial can be found at a specific URL. To achieve this functionality, you would end up with a simila ...

Check for the presence of an executable file in the system path using Node.js

Query How can I easily determine if a system executable is accessible on the system path using Node.js? For instance, if a user has Python installed at /usr/bin/python and the $PATH includes /usr/bin, how can I identify this in Node.js? Also, how can I id ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Exploring the Unpredictable Results of Recursive Functions in JavaScript

Take a look at this recursive code snippet. function calculateFactorial(n) { if (n === 0 || n === 1) { return 1; } else { console.log(calculateFactorial( (n - 1) )); return n * calculateFactorial(n - 1); } } const num = ...

Tips on transitioning a Node.js application from JavaScript to TypeScript incrementally

I have a JavaScript node application that has grown quite large and I am considering migrating to TypeScript for faster development and easier code maintenance. I have installed TypeScript along with the node and mocha types using the following commands: ...

Troubleshooting issue with Node.js Express and AWS ELB: Unable to successfully redirect from HTTP to HTTPS

Despite reading similar inquiries and solutions, I am still unable to find a fix for my issue. Below is the content of my app.js: var express = require('express'); var app = express(); app.all(function(req, res, next){ ...

White border appears when hovering over MUI TextField

I've been troubleshooting this issue for what seems like an eternity. I've combed through Chrome's inspect tool, searching for any hover styles on the fieldset element, but to no avail. Here's my dilemma... I simply want a basic outline ...

Upon refreshing the browser, an error pops up saying "unable to set headers after they have been sent."

Error image: app.get('/home', function (req, res, next) { usersession = req.session; if (usersession.loggedin == true) res.redirect('/home'); res.sendFile(path.join(__dirname, 'index.html')); }); ...

javascript Try again with async await

I am working with multiple asynchronous functions that send requests to a server. If an error occurs, they catch it and retry the function. These functions depend on data from the previous one, so they need to be executed sequentially. The issue I am facin ...

Avoiding memory leaks in Node.js with Express framework

Dealing with memory leaks in nodejs (express.js) has been a challenge for me. I followed various tutorials online, but unlike the examples provided, identifying the source of the leak in my code has not been straightforward. Through the use of Chrome Dev T ...

Pass the PHP data back to my existing webpage for JavaScript to retrieve

I recently set up a form on my WordPress website for users to submit data. Once the form is submitted, I use AJAX to create a new post without having to reload the page. I now need to figure out how to pass the post ID, a simple integer, back to the page s ...

Can you explain the variation between a standard javascript integer and one obtained from jquery.val()?

Utilizing a script known as countUp.js, I am able to increment an integer in a visually appealing manner until it reaches the desired value. This is how I have implemented the code: HTML: <h2 id="countUp-1">2500</h2> JS var theval = 5000; va ...

Issue: Dynamic server is experiencing abnormal increase in usage due to headers on Next version 13.4

Encountering an error in the following function. It's a basic function designed to retrieve the token from the session. 4 | 5 | export async function getUserToken() { > 6 | const session = await getServerSession(authOptions) | ...

A guide on accessing the first element in an array when performing multiplication within the Interval component in React.js

I am having trouble initiating an if statement from number 0 once the window is loaded, as it seems to be skipping over 0 and starting from 1 instead. Can someone please assist me in understanding how this works? showAnime = () => { let counter ...