Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs").

Below is my app.js code:

// GET API REQUEST
var url = 'https://url.tld/api/';
request(url, function (error, response, body) {
    if(!error && response.statusCode == 200) {
        var parsedData = JSON.parse(body);
        return parsedData;
    }
});

app.get("/", function(req, res) {
    res.render("index.ejs", {parsedData: parsedData});   
    });

Code snippet from header.ejs:

<li>Active players: <span><%= parsedData["players"] %></span></li>

Encountering a "parsedData is undefined" error and unsure how to resolve. The goal is to display active players and server status in the navbar. Any suggestions on common practices to achieve this?

Thank you in advance!

Answer №1

If you're facing a challenge, consider using middleware as a solution.

According to the express documentation:

Middleware functions have access to the request object (req), response object (res), and the next middleware function in the application's request-response cycle.

Tasks that middleware functions can perform include:

  • Executing code.
  • Making changes to request and response objects.
  • Ending the request-response cycle.
  • Calling the next middleware function in the stack.

In middleware, always remember to include the request, response, and the function next. After performing necessary actions, call next to proceed with the following task.

For instance, if you wish to create middleware that logs the time for each incoming request, you could write something like this:

app.use(function(req, res, next) {
  console.log(Date.now())
  next()
})

In your specific case, it might look like this:

app.use(function(req, res, next) {
  // do something
  request(url, function(err, response, body) {
    // handle data
    res.locals.parsedData = parsedData
  })
})

To display the parsed data in your res.render, use:

res.render('index.ejs', {parsedData: res.locals.parsedData})

Referencing the express documentation once more:

[res.locals is] An object containing response local variables limited to the current request cycle, available only to rendered views during that cycle.

If you know the data is required only once, store it in app.locals instead. Within the middleware, check if app.locals.parsedData exists before making the request.

I hope this explanation is beneficial!

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

The driver instance that has forked will never cease

Issues arise when attempting to run multiple browser windows in Protractor. The code snippet being tested is as follows: I create a new browser instance to perform certain tests. When input is entered into the original browser, it should not affect the ne ...

Refreshing the Mocha Server

Recently, I encountered a situation where I needed to automate some cleanup tasks in my Express server using Mocha tests. In my server.js file, I included the following code snippet to manage the cleanup operations when the server shuts down gracefully (s ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

Experienced an unexpected setback with the absence of the right-click capability on a Javascript-powered hyperlink, specialized for

I am facing an issue with a hyperlink on my website. This particular hyperlink submits a hidden form using the POST method to redirect users to another site. However, when someone right-clicks on this hyperlink and tries to open it in a new tab, they are o ...

What is the best way to link docker containers together for optimal performance?

I am currently in the process of developing a web application that consists of three main components: A Node.js API A front-end web client that consumes the API Another Node.js service dedicated to data processing My goal is to establish communication b ...

Guide on utilizing exported API endpoint in Node and Express

Seeking a deeper understanding of express and its utilization of various endpoints. Recently came across an example of an endpoint that reads in a json file, demonstrated as follows: const fs = require('fs'); const path = require('path&apos ...

The loop is being controlled but the data is not being added and shown in the HTML div

I am struggling to display JSON data in an HTML div using a for loop. While my control is entering the loop, the data is not being appended and displayed in the HTML div. Here is the JSON data: [{"id":"15","FirstName":"ranjan","MiddleName":"","LastName": ...

Check out this Angular demonstration page!

Looking to demonstrate the features of my Angular page using a plugin like intro.js, however, only part of the page is shown upon loading. Users are greeted with an input box to fill out an id and submit before the rest of the page is displayed after makin ...

"Is there a way to retrieve "Lorem ipsum" information from a web service in JSON format

Does anyone know of any sample web services that serve JSON data? I'm looking to practice consuming JSON for testing and learning purposes. I would even be interested in downloading JSON files with images and other content to study offline. Perhaps th ...

JavaScript - Modify input character prior to appending it to the text area

I am working on creating a virtual keyboard using jQuery. Whenever I press 'a' in the textarea, I want it to display 'z' instead. In my investigation of typing a letter in the textarea, I discovered the following sequence: keyDown ev ...

What's the best way to correctly update the selection of chokidar files without the need to create a

If the files selection that should be watched changes after creating a chokidar instance, is it possible to simply assign the new chokidar watcher with the updated files selection to the same variable without creating a new one? In the code provided belo ...

Seamless scrolling experience achieved after implementing a header that appears when scrolling up

My goal is to create a header with the following functionalities: Initially displays with a transparent background Upon scrolling down the page by 25px, it will dynamically add the header--maroon class to the header, which alters the background color and ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

Issues with jQuery slide operation

I'm facing an issue with jQuery and I can't figure out where it's coming from. Here is the error message that keeps showing up in the console: Uncaught TypeError: Object [object Object] has no method 'getElement' script_16.js:46Un ...

How to locate the index.js file within my application using Node.js?

Directory Structure bin - main.js lib - javascript files... models - javascript files... node_modules - folders and files public - index.html route - javascript files... index.js package.json I am using Express and angular.js. The ser ...

What are the steps to implement the jQuery slide menu effect on a website?

When visiting the website , you may notice a symbol positioned in the top left corner of the site. By clicking on this symbol, a sleek div will slide out. How can this type of animation be achieved through javascript or jquery? ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

Refresh two angular-datatables

I'm facing a challenge when it comes to updating two datatables simultaneously on the same page. Here's how my HTML is structured: <table id="datatable1" ng-if="Ctrl.dtOptions1" datatable="" dt-options="Ctrl.dtOptions1" dt-column-defs="Ctrl. ...

Obtain a collection of strings from an array of objects based on specified criteria

What is the most efficient method to extract an array of specific strings from an array of objects, where a certain condition needs to be met? Solution Attempt: const array = [{ "Item": "A", "Quantity": 2 ...