Attempt to capture a parameter transmitted from res.render

Within my ejs webpage, I am implementing a try catch block within a script tag.

Sometimes when rendering the page, my server includes the token and user, while other times it does not. In previous instances where variables were passed through, I would use

var x = <%- JSON.stringify(x) %>;
. However, this time, due to nothing being passed in, an error occurred.

The main issue I'm facing is that despite trying to initialize these variables, they do not seem to work as intended. Here is the code snippet:

try {
            var Token = <%- JSON.stringify(Token) %>;
            var User = <%- JSON.stringify(User) %>;
        }
        catch(err){
            console.log("there is no token/user");
        }

My intention is for the code to attempt to set these variables if they are passed in from the server's res.render function. If not provided, the code should continue execution without any problems.

Answer №1

It is not possible to use a try/catch block to catch syntax errors.

Instead of relying on error handling, one approach is to provide default values for variables in case they are not set.

var Token = <%- JSON.stringify(Token || "") %>;
var User = <%- JSON.stringify(User || "") %>;
if (Token == "" || User == "") {
  console.log("there is no token/user");
}

Answer №2

let isTokenPresent = false;
let isUserPresent = false;

 <% if (Token) {
    isTokenPresent = true;
}
if (User) {
    isUserPresent = true;
} %>

if (isUserPresent && isTokenPresent) {
    let TokenData = '<% - JSON.stringify(Token) %>';
    let UserData = '<% - JSON.stringify(User) %>';
} else {
    console.log("No token or user found");
}

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

Enhance the axis functionality in c3.js

My goal is to display a user's financial data for the previous week, but sometimes they may not have data for all seven days. When using c3.js, I noticed that it automatically extends the 'endpoint-value' to the end of the axis. Is there a w ...

Leave a message | Google Sheets | JavaScript using nodeJS

I am having trouble adding comments to cells using the "Google Spread-Sheet" module in NODEJS. I have successfully written to cells, read from them, and deleted them, but I can't figure out how to add a comment to a cell. The tutorials I have found on ...

Having trouble accessing dynamically generated elements using Selenium

I've been attempting to change the router's SSIDs using a Selenium script, but I'm encountering difficulty accessing any JS elements generated by the router page. I've tried various Expected Conditions and methods without success. Here ...

Tips for altering the background shade of a chosen element within a list in ReactJS

Can someone assist me in changing the background color of a selected item from a list and retrieving the value of the selected item? Any help would be greatly appreciated. Thank you! Below is the code for my Component: const Time = () => { const data ...

Issues with AngularJS Validation not functioning properly with File Inputs marked as 'Required'

I've been experimenting with this issue and haven't been able to solve it. While creating an Angular form, I found that validation works fine when the required attribute is used in a text field. However, when I tried adding a file input type with ...

Using AngularJS to pass objects dynamically through ng-include

Below is an example that is fully functional, except for one issue. When using node.title within the HTML code, everything works as expected. However, when trying to use {{node.title}} within the ng-include file, it does not function properly. Only the g ...

Using Vue.js to showcase Unicode, hexadecimal emojis, and octal literals in HTML

Received this response from the webserver: "\ud83d\ude48\ud83d\ude02\ud83d\ude30\ud83d\ude09\ud83d\udc4f\ud83c\udffd\ud83d\udc4c\ud83c\udffd\ud83d\udd1d\u2714&b ...

Array not transmitted via jQuery ajax

I am attempting to use the jQuery ajax function to send an array, but for some reason it is not functioning as expected. Below is the code I have been working with: if (section_name == "first_details_div") { var fields_arr = ["f_name", "l_name", "i ...

Struggling to store the canvas data, the file ends up blank

I've been attempting to upload an image from a canvas to a server using ajax, but every time I end up with an empty image file that is only 879 bytes. I can't seem to figure out what I'm doing wrong. If someone could take a look, I would gre ...

stop a element from being removed from the document

Is there a way to stop an element from being removed using something similar to preventDefault()? For example: myNode.on("remove", (e) => { e.preventDefault(); }); I have tried using MutationObserver to detect the removal, but so f ...

What methods can I use to identify if the browser my users are using does not have support for Bootstrap 4?

My recent project heavily utilizes the advanced features of Bootstrap 4/CSS, making it incompatible with older browsers still in use by some of my visitors. How can I effectively identify when a user's browser does not support bootstrap 4 so that I c ...

Is there a way to retrieve the browser console log with Selenium and Java?

Seeking advice on capturing logs for any JavaScript event triggers or errors using Selenium and Java. Any suggestions would be greatly appreciated. I have attempted the following code, but it does not seem to be working as intended: public void HomePage ...

Testing React components with Jasmine

I need some guidance on how to properly integrate the Jasmine test runner into my React app without using Karma. Currently, I am deploying my test cases to a TV and running the standalone spec runner on the set. To do this, I had to inline and transpile th ...

Trouble with loading custom stylesheets and scripts using functions.php in Smoothstate.js

Seeking assistance with an issue I'm experiencing. Currently using the Smoothstate.js plugin to navigate pages on my Wordpress site. The plugin is working well for the most part and fulfilling my requirements. However, when attempting to load separat ...

PlaneGeometry at x=0 y=0 z=0 for three.js on a flat surface

Hi there! I have a code snippet that currently renders an image vertically, and I'm looking to modify it so that the PlaneGeometry is drawn horizontally instead. Rather than rotating it with mesh.rotation.x=THREE.Math.degToRad(-90);, I'd like it ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

Harness the Power of Asynchronous Binding in Knockout.js

I'm really struggling to figure out how to asynchronously bind my cascading Select2 drop-down fields using knockoutJS. Everything works perfectly fine when the data is static within the function, but as soon as I introduce an asynchronous ajax call, ...

How do I retrieve child nodes' properties in JavaScript?

I am currently working on a link extractor using CasperJS, and the core function looks something like this: function extractLinks() { return Array.prototype.map.call(document.querySelectorAll('a'), function(e){ return { ...

What are the steps to modify the relative URL when using Express proxy?

To prevent the common CORS issue with client-side JavaScript code, I utilize a Node.js Express server. The server is configured with the following code: var app = express(); app.all('/Api/*', function (req, res) { proxy.web(req, res, { ...

Creating a Bar Chart in d3js with time on the x-axis and one or multiple sets of numerical data on the y-axis: a step-by

My webpage structure is as follows: <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="css/style.css" rel="stylesheet" /> &l ...