The conditional statement in EJS is not functioning properly

I have been incorporating the ejs template into my express application. Following the guidance on the official page of the template (https://www.npmjs.com/package/ejs), I am utilizing an if conditional to display a variable only if it has been defined. Here is an example:

<% if (msg) { %>
  <h2><%=msg %></h2>
<% } else { %>
  <h2>There are no messages</h2>
<% } %>

The issue I am facing is that each time I implement this, the server returns a 500 error. How can I troubleshoot and resolve this problem?

Answer №1

The error occurs when you try to use if (msg).

To solve this issue, consider checking for existence in a different way, such as using typeof:

<% if (typeof msg != "undefined") { %>
<h2><%=msg %></h2>
<% } else {%>
<h2>No messages available</h2>
<% } %>'

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

Implementing event listeners with AngularJS after making a POST request

As I delve into the world of development, please forgive my lack of knowledge. My search for solutions brought me here. I am currently working on a comment and reply app. In order to add comments to my view, I am utilizing this specific function. $scope.i ...

Next.js is like Gatsby but with the power of GraphQL

I'm curious if it's possible to set up GraphQL in Next.js similar to how it's done in Gatsby, allowing me to query pages and retrieve data from them. Are there any plugins available for Next.js that work like Gatsby-file-source and gatsby-ma ...

Localhost file not refreshing

I'm feeling quite frustrated at the moment. It seems like such a simple issue, but I can't seem to figure it out. I have created a basic webpage with a "tree-view" structure. In my readjson.js file, I am reading from a json file located in json/ ...

Discover the Location and Sign Up for Angular2+ Service

I'm currently using the Google Maps API to retrieve a user's geoLocation data, including latitude and longitude. My goal is to pass this information to a web API service in order to receive JSON output of surrounding addresses. I have implemented ...

I'm not sure why the Mongoose populater is returning a null value

I'm struggling with English and need some help. Here are two schemas and a query I've been working on: /models/user_schema const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const { Schema } = mongoose; ...

Tips for extracting certain characters from a URL and saving them as an ID using JavaScript

Consider this scenario where I have a specific URL: http://localhost:3000/legone/survey/surveyform/form11/03141800300000030001 In order to achieve the desired outcome, I aim to extract and store different parts of the URL into designated IDs. Specificall ...

Passing a value through jQuery Ajax when selecting an option (onchange) to store in a PHP variable on the same page without

How can I retrieve the selected value using PHP and update a specific div element with it? <div id="test"> <?php if (isset($_POST['sweets'])) { ob_clean(); echo $_POST['sweets']; exit; } ?> ...

Express server experiencing a backlog of POST requests after receiving six requests from the same browser, resulting in unexpected or unusual behavior

My application is experiencing delays in processing post requests when multiple requests are sent within a short timeframe. This results in unexpected behavior. For instance: app.options('/',cors({origin: "http://localhost:5050"})); ap ...

Extract the JSON file data by eliminating the indexes (1,2,3..) and transforming it into an array format

Here is the content from the JSON file: { "1": { "Order Number": "CA-2017-126221", "Order Status": "Completed", "Order Date": "30/12/2017", "First Name (Billing)": "Abdul", "State Code (Shipping)": "SD", ...

Ways to continuously monitor a div for a specific class

Is there a way to continuously check if an area has the class "top-nav" in order for the alerts to work every time it lacks or contains the class? How can I achieve this functionality? Check out the code on jsfiddle: https://jsfiddle.net/jzhang172/117mg0y ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

Issue encountered while attempting to utilize the concat method to condense an array

Describing the Problem: I am facing a challenge with flattening an array of sales data. Each element in the array contains an ID, sale code, seller username, timestamp, and details which include an array of products, quantities, and subtotals for each item ...

Setting up Vue CLI 4 with ESLint, TypeScript, Stylelint for SCSS, and Airbnb rules in the VS Code editor with automatic fixes on save

After struggling with configuring Vue CLI 4 with ESLint, Prettier, Airbnb rules, TypeScript, and Vetur, I found myself at a crossroads. The challenges continued to mount as the nature of the problem evolved from my previous attempts.: How to configure Vue ...

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

Extract data from an array in MongoDB by organizing it into sections based on dates

As a beginner in the world of MongoDB, I'm trying to figure out how to extract data from an array in separate sections. { "name":"User name", "messages":[ { "message":"Message 1", ...

Caught up: TypeScript not catching errors inside Promises

Currently, I am in the process of developing a SPFx WebPart using TypeScript. Within my code, there is a function dedicated to retrieving a team based on its name (the get() method also returns a promise): public getTeamChannelByName(teamId: string, cha ...

Mastering the art of linking asynchronous callbacks based on conditions

I have a node.js express project where I need to create a switch-to-user feature for admin users. The admin should be able to enter either a username or user-id in a box. Below is the code snippet that handles this functionality. The issue arises when th ...

Issue encountered while trying to import CSV file into MYSQL database: Error code 1136 - ER_WRONG_VALUE_COUNT_ON_ROW

As someone who is new to Node and Ajax, I am in the process of trying to import a csv file into a MySQL table. Despite following tutorials, I seem to have made some mistakes along the way. Any help you can offer would be greatly appreciated. Although I ha ...