Utilizing the local variables of Express in front-end JavaScript

I've been struggling with implementing this code on my project, despite there being similar posts on the topic.

Here is the basic rendering function I am using:

router.get("/", function(req, res) {
  res.render("index", {
    route: "one"
  });
});

However, I have been unable to access the route variable in my client-side JavaScript file. I've tried a few methods, but none seem to be working:

// Unexpected token: <
var route = <%- JSON.stringify(route) %>;

// variable 'route' is undefined
var route = !{route};

// Unexpected token .
var route = !{JSON.stringify(route)};

// console log out "<%- JSON.stringify(route) %>;
var route = "<$- JSON.stringify(route) %>";

It's worth mentioning that my view engine is ejs.

Answer №1

Perhaps experimenting with this approach could yield better results:

router.get("/", function(req, res) {
  res.render("index", JSON.stringify({
    path: "example"
  }));
});

Then utilize JSON.parse on the client side.

Explore more about body-parser on GitHub

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

Guide for sending token through Authorization in Laravel 8 API

I am currently utilizing Laravel 8 as an API REST and encountering an issue where my token is null when sent in the AJAX request. I have successfully handled logins and requests without tokens, but this specific scenario has me puzzled. Within my JavaScri ...

What is the best approach for transmitting file and form data from an AngularJS application to a Node.js server?

Salutations! I am in the process of developing a MEAN application with a video upload form. However, I have encountered an issue while making a POST request in AngularJS to my API - the data is not reaching my controller. Can anyone point out where I might ...

Tips for creating a div element that closes on the second click:

On the PC version, I have three blocks that open and close perfectly when clicked. However, on the mobile version, when I click on one block, it opens but does not close unless I click on another block. Additionally, if I click again on the same block th ...

Oops! The requested page "/api/auth/[...nextauth]" is missing the necessary "generateStaticParams()" function, thus making it incompatible with the "output: export" configuration

Currently, I am working on a Next.js project where I have successfully implemented user authentication using next-auth with the Google Provider. However, while attempting to build the project, an error is being thrown by the compiler stating: "Error: Page ...

JavaScript - Separate Artist and Title

In the code snippet below, I am using a Parser script to extract metadata from a live streaming radio station: const Parser = require('../src'); const radioStation = new Parser('http://stream.com/live_32.aac'); radioStation.on(' ...

Why isn't my jQuery callback executing after specifying complete:?

My current challenge involves creating an animation to remove content from the screen by gradually decreasing the opacity to 0. After this, I wish to set the visibility CSS property to hidden. To ensure that these actions occur in the correct sequence, I h ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

Using jQuery to transfer array values to a different group of elements

Looking for help with this code snippet: jQuery(document).ready(function($) { var i = 0; var values = []; var element = $('.source'); element.each(function(i) { values[i++] = $(this).text(); }); }); I'm tryi ...

Leveraging AngularJS $filter in conjunction with ng-disabled

I have a variable in my $scope that contains information about an election, including a list of voters with unique IDs: $scope.election = { voters: [ { _id: '123' }, { _id: '456' }, { _id: '789' } ] } Additio ...

Is your Javascript code for the Donate button functioning properly in Chrome but encountering issues in Internet Explorer and Firefox? See my attached code for troubleshooting

My code is working fine on Chrome without any errors, but it is not functioning properly on Mozilla and IE. Here is the script: <script type="text/javascript> function Donate() { var myform = document.createElement("form"); myform.ac ...

The Query Parameter in Twitter V2 Get Tweets API is malfunctioning

I'm trying to access detailed information about a tweet using the Twitter API documentation, but I'm running into issues. The response I get from the API for a tweet is limited: { edit_history_tweet_ids: [ '1766576440005333244' ], i ...

Conceal the Tab Bar in Stack Navigator Excluding the tabBarVisible Setting

I discovered some solutions using outdated versions of navigation, specifically involving the "tabBarVisible" option in Tab Navigator. However, this option is no longer available, so I am seeking guidance on how to hide the Tab Bar on specific screens with ...

Issue with ng-file-upload and Busboy causing upload error on server

I am facing a situation where I need to upload both a .zip file and a .xlsx file to an endpoint simultaneously. On the client side (Angular 1): files.upload = Upload.upload({ url: '/api/files', data: { xlsxFile: xlsxFile, zipFile: zipFile } ...

Connecting Vue.js components together

I have two separate components - one for viewing data and another for editing the same data. The viewing component contains labels and paragraphs, while the editing component includes inputs and textareas. Both components are fed the same data object. Is ...

Looking for assistance with REGEXP to handle a 404 path rendering issue

I am attempting to utilize REGEXP in order to display a 404 page within a react app based on the path, but I am struggling to make it work. This is the specific REGEXP pattern I am trying to achieve: The entire path should not be '/' and should ...

Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second ...

Preventing users from using alt+tab on an IE8 aspx web page

I need help with disabling the alt+tab function in my IE8 web browser for a page that displays a modal dialogue. Can anyone assist me with this issue? ...

Use ajax, javascript, and php to insert information into a database

Issue at Hand: I am trying to extract the subject name from the admin and store it in the database. Following that, I aim to display the query result on the same webpage without refreshing it using Ajax. However, the current code is yielding incorrect outp ...

Angular 6 canvas resizing causing inaccurate data to be retrieved by click listener

The canvas on my webpage contains clickable elements that were added using a for loop. I implemented a resizing event that redraws the canvas after the user window has been resized. Everything works perfectly fine when the window is loaded for the first ti ...

Navigate the scroll bar horizontally one by one instead of all at once, due to a width problem

The issue I'm facing involves determining the correct width for scrolling left or right. This results in the navigation tabs not scrolling correctly one by one. Each time I click the scroll right button, it adds more width than necessary and causes th ...