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

Unable to "serialize" geoJSON information

While working with Leaflet JavaScript, I am attempting to retrieve data directly from GeoServer using an Ajax link. To display it nicely in a DataTables table, I need to convert it into JSON format as per DataTables instructions. However, I keep encounteri ...

Utilize jQuery to extract the content, rearrange the content, and then encapsulate it within fresh

I attempted all day to rearrange this menu the way I want, but since I am new to jQuery, I'm facing some challenges. Here is what I am currently trying to achieve: Inside the last td.top of this menu, there are 3 ul.sub li items. I aim to extract ...

The functionality of JQuery Fancybox seems to be malfunctioning when attempting to integrate data retrieved from a

$.getJSON("/Home/AjaxBrowse", { page: p ? p : 1 }, function (data) { var output = ""; jQuery.each(data.users, function (key, value) { output += '<li>' ...

What are the best solutions for tackling EJS-related problems?

I encountered an error in my Node.js application. The issue arises when using the EJS template for page rendering. The EJS template engine is displaying an error. app.set('view engine', 'ejs'); //app.set('view engine', 'p ...

ES modules' `require()` functionality is not supported

Issue: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\...\node_modules\normalize-url\index.js [0] require() of ES modules is not supported. [0] require() of D:\...\node_modules\normalize-url\index.js ...

Error: Trying to modify headers after they have already been sent in an Express application built with Node

I've been working on creating a template using express and ejs, but I can't seem to find a solution. I've tried multiple things like next() Here's the snippet of my code that is causing issues: app.get('/', function (req, re ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed fr ...

Why does JavaScript often return the constructor of an object instead of false?

Seeking assistance in resolving issues with the functionality of my script. function CatFactory(cat) // Cat constructor { for (y in cats) { if (cats[y].color == cat.color) {return false;} // return false if already in the array ...

What is the best way to enable autocomplete in AngularJS?

I am working with an object that contains both a name and an ID. I want to implement autocomplete functionality based on the name property. Below is the code snippet that I have tried: //Js file var app=angular.module("myapp",[]); app.controller("controll ...

Struggling to loop through a child in Firebase real-time database?

I'm struggling to retrieve a nested child from my database with the following structure https://i.stack.imgur.com/ZDs38.png I am attempting to get the URI from the Gallery object. When I log in, I can see this in the console https://i.stack.imgur.c ...

Unfulfilled commitment on bcrypt

I am currently facing an issue while trying to validate a user's password using bcryptjs. I have implemented a function that returns a Promise, but I am encountering an error when reaching the bycrypt.hash step - all I see is Promise { <pending> ...

monitoring checkbox status in vue?

When using Vue, I have created dynamic checkboxes that display as shown below: <li v-for="element in checklist" :key="element.id" class="block w-full p-1"> <div v-if="element.taskId == task" clas ...

Use Javascript to display specific div elements by clicking a button

I could really use some assistance, When I attempt to display the select div by clicking the button, the "id" that PHP generates returns a null response in the console. The requirement is to only show the div when clicking on the "Quick Quote" button. Pro ...

Leveraging the combination of Express JS and Vue.js within the Electron framework

Can you combine Vue.js and Express JS in a project with Electron JS? How would this work? I currently have a project running on Vue.js and Electron JS, but I'm unsure how to integrate Express JS into it. Any guidance would be greatly appreciated. ...

Sending JSON data through an AJAX call results in an empty array being received

Recently, I've been attempting to send data through ajax using the following information: var jsondata = {"address" : [ { "id": addid, "streetaddress": streetaddress, "city": city, "state": state, "zipcode": zipco ...

When I changed the encoding of a live texture to sRGB in Three.js, the frame rate dropped by fifty percent

I am currently working on a threejs application that requires updating a texture in each frame. The output encoding of the THREE.WebGLRenderer is set to sRGB. Upon setting the texture encoding to sRGB, I observed that the rendering result is accurate. How ...

What is the recommended way to select a checkbox using JQuery?

I have exhausted all options and nothing seems to be working. This is the checkbox in question: <input type="checkbox" onchange="WriteFormSelections('SearchForm', 'AccommodationType', 'AccommodationTypeSelections', 'A ...

Update the section tag upon submission using jQuery on a jQuery Mobile HTML page

I have integrated a jquerymobile template into Dreamweaver 6.0 to create a mobile app interface. The home screen features four buttons - specifically, View, Create, Update, Delete. Upon clicking the Create button, a new screen is opened (each screen corres ...

Using a regular expression to extract the ID from a JSON string. The ID that comes after the occurrence of "State Code":

Can someone help me with a regex that can match the ID:1234 in the following code snippet? { { Id:"", "Address": { "Deleted": false, "Owner": 123, "PartyId": 123, "Modified": "11:41:29", ...