Guide on utilizing JSON data sent through Express res.render in a public JavaScript file

Thank you in advance for your assistance. I have a question that has been on my mind and it seems quite straightforward.

When making an app.get request, I am fetching data from an external API using Express, and then sending both the JSON data and a Jade file through res.render.

I have successfully managed to manipulate this data within Jade files and JavaScript embedded directly into the Jade file.

However, I am struggling to figure out how to work with this JSON data from a separate JavaScript file referenced by the HTML output.

For instance:

router.get('/dashboard', function (req, res, next) {

  // Fetch and parse data from the external API

  res.render('dashboard', {
      data: data
  });

});

The dashboard.jade file utilizes this data to perform various tasks.

if #{data.isNew} === true {do cool stuff}

I have also written JavaScript code that interacts with this data within the dashboard.jade file itself. However, I would prefer to write and incorporate this JavaScript in a separate file named scripts.js that is linked from the Jade file.

script(src='scripts.js')

Unfortunately, I am unable to access this data - I have attempted different syntaxes but have not succeeded.

Therefore, my query is this - how can I effectively handle JSON data that has been sent via res.render() to a view, when working with a JS file referenced from that rendered view?

Answer №1

To display data in dashboard.jade, you must first create a variable using interpolation:

 script.
   var myData = #{JSON.stringify(data)};

This will convert the data into a string that can be accessed by any scripts running on the page through Jade engine.

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

Unlock the secret to retrieving specific properties from a JSON object

Whenever this code is executed: import requests import json def obtain_sole_fact(): catFact = requests.get("https://catfact.ninja/fact?max_length=140") json_data = json.loads(catFact.text) return json_data['fact'] print(obtain_s ...

How can Express JS be configured to make URL calls from a local environment?

I encountered an issue with my code (Weather App using OpenWeatherMap Api) when I attempted to move my apiKey and apiUrl to the .env file. An error appeared in the terminal, but it's unclear why it occurred. Below is my code: const express = require( ...

Angular Kendo dropdownlist and input textbox are not working together as anticipated

I'm looking to implement a dropdown list similar to Google search using Kendo Angular. However, I've encountered an issue where entering text in the textbox and pressing "Enter" passes the first matching value from the dropdown list to my compone ...

Choose the list item by identifying the corresponding unordered list

Is there a way to target the second li element within an ul list like this: HTML <ul> <li></li> <ul> <li>This one is what I need to select</li> </ul> </ul> ...

Discovering the content within table cells by utilizing JavaScript functions linked to specific IDs

I am currently working on a project that involves a dropdown list: <select id="itemsList" onchange="gettingList()"> <option>Please choose an option</option> <option value="50">Shampoo</option ...

Synchronize two slideshows in a cycle with timed delays between each cycle

Is there a way to add a sequential delay between slideshows in the synchronized slide show example from cycle2 API? For example, having each div.cycle-slideshow start at 5s intervals (5s, 10s, 15s, 20s...). The cycle would then repeat with the first div st ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

Node.js: Deciding between res.render and res.redirect in express-session

On my website, I have a login page and a myservices page. Once a user logs in, they should be redirected to the myservices page where their username is displayed. In the login.js file, the following code is used: req.session.user = "abc"; res.redirect(&a ...

How come the back button does not initiate client-side navigation in a Next.js application?

In my Next.js application utilizing GraphQL to fetch articles from a server, I encountered an issue with dynamic routing when reloading the page while on an article and attempting to navigate back. The usual scenario works as expected: Index -> [slug] ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

Transferring information between Express and React through the Contentful API

I have embarked on a journey to explore Contentful's headless CMS, but I am encountering a challenge with their API client. My goal is to combine Express with React for server-side rendering, and I am utilizing this repository as my starting point. S ...

What is the best way to pass query strings from React to the backend?

import React, { useEffect, useState } from "react"; import { Form, Row, Col, Button } from "react-bootstrap"; import { useParams, useNavigate } from "react-router-dom"; const FilterComponent = ({ categories, brands }) => { ...

Displaying concealed fields using the Bootstrap table detail formatter

I am attempting to create a customized detail formatter for my table, but I am encountering several fields with underscores, such as: _id: undefined _class: undefined _data: [object Object] This occurs when I click the plus button. <head> &l ...

Tips for concentrating on the initial input field produced by an ng-repeat in AngularJS

Currently, I am dynamically generating input fields using ng-repeat and everything is working smoothly. However, my requirement is to set focus on the first input that is generated by this ng-repeat based on their sequenceId values. So far, I have attempte ...

Python JSON: NameError: name 'false' is not recognized

While attempting to json.load this dictionary extracted from a tweet on Twitter: {"created_at":"Thu Jul 10 20:02:00 +0000 2014","id":487325888950710272,"id_str":"487325888950710272","text":"\u5f81\u9678\u300c\u5de6\u8155\u306 ...

The ng-model remains unchanged when the <select> element is modified using JavaScript

I am currently working on creating a customized dropdown box with the help of JavaScript and anglersJS to connect the data with the select element. The user interaction involves clicking on a div element that is styled to act as the dropdown option. This d ...

What is the process for saving selected values from a drop-down list into a database?

Hey there, I'm a newcomer to PHP and ajax. When choosing an option from the drop-down list, a separate div function should appear where I need to insert both the selected option and input data in different divs. Sorry for my poor English. Any help fro ...

Using Ajax (Jquery) to send data to a PHP script

Currently, I am working on an application where users can click a checkmark to complete a task. When this action is taken, a popup window appears (created using bootstrap), prompting the user to enter their hours worked on the task. After entering the hour ...

Tips for maintaining the node-dbox token across page reloads in a Node.js/Express environment

I am currently working on developing a small application using NodeJS, node-dbox, and Express. The process for obtaining authorization from DropBox involves three steps, as outlined in this guide. First, the request token needs to be obtained, then the use ...

javascript detect when two div elements are overlapping

On my webpage, I have implemented the effect.shrink() function. However, when clicking quickly on the page, the div tags start overlapping with other elements. What is the best way to solve this issue? I am using both scriptaculous.js and prototype.js fo ...