Utilizing Express and ejs to display a JSON using the "<%" tag

I am facing an issue with the code in my index.ejs file. The current code snippet is as follows:

var current_user = <%= user %>

In my node.js file, I have the following code:

app.get("/", function(req, res){
    res.locals.user = req.user
    res.render("index")
})

However, when I view the page, I see that it displays "var current_user = [object Object]". Upon trying to stringify the user object using this code:

var current_user = <%= JSON.stringify(user) %>

The result is:

var current_user = {&quot;__v&quot;:0,&quot;_id&quot;:&quot;50bc01938f164ee80b000001&quot;,&quot;agents&quot;:...

I am looking for a way to pass a JSON object that will be easily readable by JavaScript. Is there a solution for this?

Answer №1

That task turned out to be quite simple, just avoid using <%= and opt for <%- instead. This code snippet demonstrates how:

 <%- JSON.stringify(user) %>

The former will display in HTML format, while the latter will show variables as they are without evaluation.

Answer №2

Important!

When creating a user through API calls, utilizing <%-= can result in a critical XSS vulnerability. For possible solutions, refer to this resource:

Securing JavaScript in API Calls

Answer №3

For those of us who have objects that contain special characters like / or ", it's important to use a resilient solution like the one provided below:

var current_user = <%- JSON.stringify(user).replace(/\\/g, '\\\\') %>

Answer №4

The most recent version of Express now supports this functionality

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 Data Table experiences intermittent hanging issues (Table is empty) when sorting or loading data with Knockout binding

While working on a project, I encountered an issue with binding data to a table using Knockout JS and the JQuery/Bootstrap based; Data Table API. The problem was that the table would become unresponsive at times when sorted or loaded, without any errors be ...

Passing an array from PHP to the DataTables JavaScript library

I am attempting to pass a PHP array to the JS Datatable library for testing purposes. Instead of fetching data from a database, I have simplified my approach. Here is a basic representation of my PHP code: $data_fmt['data'][] = array("TEST"); e ...

Verifying internet connectivity and updating content using jQuery and JavaScript

Upon loading the page, the following functionality occurs without triggering a click event: The updated code attempts to determine if the internet connection is active. If the connection is off, the 'link' on the page will be disabled (non-click ...

issue with webpack-dev-server not refreshing after changes to HTML or Sass files

Here is the layout of my project: \root \webpack.config.js \public \ index.html \ ... \ css \ directives \ views \ dist (webpack output) \app.js ...

Styled-components is not recognizing the prop `isActive` on a DOM element in React

In my code, I have an svg component that accepts props like so: import React from 'react'; export default (props) => ( <svg {...props}> <path d="M11.5 16.45l6.364-6.364" fillRule="evenodd" /> </svg> ) ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

There was a dependency resolution error encountered when resolving the following: [email protected] 12:15:56 AM: npm ERR! Discovered: [email protected] . The Netlify deploy log is provided below for reference

5:27:42 PM: Installing npm packages using npm version 8.19.3 5:27:44 PM: npm ERR! code ERESOLVE 5:27:44 PM: npm ERR! ERESOLVE could not resolve 5:27:44 PM: npm ERR! 5:27:44 PM: npm ERR! While resolving: [email protected] 5:27:44 PM: npm ERR! Foun ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

Tips for partitioning an element using Selenium and Appium when it lacks a distinctive ID, class, package, or resource identifier:

I am currently trying to determine if I am receiving the expected response from a text message. In order to do this, I need to access the text view of the incoming message. The challenge I am facing is how to distinguish between the received text and the s ...

An error message was returned when trying to decode the array using json

I have a PHP program that accesses a .txt file and decodes the JSON to insert the user's email and name data into my campaign monitor database. The JSON format is strange because new entries use a ][ sequence as shown in this example: [{"email":"< ...

Utilizing JSON File as an Array in a Node.JS Environment

I'm struggling with converting a .json file into an array object using NodeJS, Here's the JSON content: { "cat": { "nani": "meow" }, "dog": { "nani": "woof" } } index.js: const array = require('../../data/use ...

Leveraging electron-usb alongside electron

I attempted to integrate the electron-usb library into my electron project. Upon running npm start with require('electron-usb') in my index.html file, an error is displayed in the console: Uncaught Error: The specified procedure could not be fo ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

How can I create a hover effect animation in React?

I am looking to replicate the menu item underline animation demonstrated in this example. In jQuery, I would easily achieve this by obtaining the left position and width of a menu item, then using stop.animation on hover. Attempting this animation with R ...

The window failed to redirect to the intended URL provided by the Json response

function GetOpenUrl(transactionId, legacyIndication) { var json = { id: transactionId, legacyIndication: legacyIndication }; $.ajax({ type: "POST", url: "<%= Url.Action("OpenSa ...

Could there be any concerns with simultaneous connections to a Node.js application hosted behind nginx?

I've been trying to determine if there are any potential issues with simultaneous connections to an upstream server in nginx. My nginx configuration follows the standard setup: upstream nodejs_app { server 127.0.0.1:3000; } server { listen 80; ...

ReactJS encounters errors even when the backend is returning a 200 OK status code

My ReactJS frontend receives an error when sending a GET request, even though the django backend terminal shows [10/Mar/2018 23:31:08] "GET /post/ HTTP/1.1" 200 930. I am using redux sagas in my project. In src/index.js: (index.js code snippet here) In ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...