express-flash-notification displays the following error message: "No default engine was specified and no extension was provided."

Recently, I started working with node.js and using MEAN stack for my project. In the footer of my project, I have an option to "Subscribe email". Due to constraints in the architecture, I am unable to utilize Angular for displaying flash messages as I don't have a controller. Therefore, I need to display the flash message using plain node.js.

Below is a snippet from my server.js file:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var session = require('express-session');
var flash = require('express-flash-notification')
var cookieParser = require('cookie-parser')

app.use(cookieParser("hash"));   
app.use(session({secret:"hash", cookie: { maxAge: 60000 }, resave: true, saveUninitialized: true }))
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(flash(app));
app.use(express.static(__dirname + '/client'));
app.use('/admin', express.static(__dirname + '/admin'));
app.use('/', express.static(__dirname + '/client', { redirect: false }));

app.post('/subscribe', function (req, res) {
    if(req.body.name == '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="422323362a2b30232502252f232b2b2e6c212d2f">[email protected]</a>') 
    {
        req.flash('info', 'Thank you', 'home');
    }
    else
    {
        res.send(500);
    }
});

app.listen(3000, function(){
    console.log('server is running on port 3000..');
});

And here's a snippet from my html file:

<!DOCTYPE html>
<html lang="en">

<body>
    <!-- footer -->
    <div>
        <form action="/subscribe" method="POST">
            <input name="name" id="name" type="text" placeholder="Enter your email address" /><input type="submit" name="submit" id="submit" class="newsletter-submit" />
        </form>
    </div>
</body>
</html>

The issue I'm facing is that it shows an error stating "No default engine was specified and no extension was provided." I have tried using {{info}} to display the message in the HTML page but it's not working as expected.

If anyone has any suggestions on how to fix this or alternative ways to show the message in the HTML page, I would greatly appreciate it.

Thank you!

Answer №1

Make sure to include the view engine in your project setup. For instance, you can opt for Jade by adding the following line of code:

app.set('view engine', 'jade');

If you prefer a more HTML-friendly syntax, consider using EJS instead and save your files with a .ejs extension.

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

To render your flash variables, utilize res.locals variables within a middleware function before defining routes:

res.locals.info = req.flash.info;

Now you can access the {{info}} variable directly through the res.locals object.

Answer №2

To address this issue, I utilized an ajax request method

<form onsubmit="sendData()" method="POST">

    <input name="username" id="username" type="text"  placeholder="Please enter your username" />
<input type="submit" name="submit" id="submit" class="submit-button" />


</form>
<label id="output" class="feedback" style="display: none;"></label>

Here's the ajax implementation

function sendData()
  {
     var data = { username: $('#username').val() };
       $.post( '/subscribe', data, function(response)
       {
         $('#output').html(response);
     });
  } 

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

I am encountering some difficulties in the installation process of Angular CLI

Encountering an error trying to install angular cli despite updating both node and npm. https://i.stack.imgur.com/SpkNU.jpg ...

Troubleshooting React and NodeJs Fetch Problem

I am currently working on retrieving data from my API, which is functioning properly. The API endpoint I am trying to fetch results from is http://localhost:5000/api/continents. {"data":[{"continentId":3,"CName":"Atlantis"},{"continentId":2,"CName":"Devia ...

Error Message: Unable to Locate File in NestJSExplanation: The specified file could not

I'm encountering an issue with my nestJS app not being able to read my cert secret file or even a basic text file. The error message I'm receiving is: ERROR [ExceptionsHandler] ENOENT: no such file or directory Here's the code snippet whe ...

What is the best way to remove all dependencies listed in the package.json file on a global scale when using N

When I have a package.json file in the root of my application and run npm install -g, it will globally install all dependencies specified in package.json. However, the opposite doesn't seem to work as expected. Upon running npm uninstall -g from my ...

What is the best way to establish and maintain lasting connections with the Firebase database while utilizing the superagent

Currently, I am following the Firebase Functions documentation on enhancing Firebase database performance. I have provided the code snippet below for your reference. const request = require('superagent'); const functions = require('fireba ...

How can one effectively extract data from a database in a React application?

We have a basic react app with authorization, utilizing JWT tokens and Redux for state management. Personally, I find the code quite complex and obfuscated, making it challenging to grasp fully. However, let's set that aside. Upon login, a token is s ...

Encountering timeout issues while testing promises in supertest-as-promised with mocha

As I work on testing a function example, here is what I have: function generateJwt(){ var deferred = Q.defer(); deferred.resolve({ message: 'user created', token: signedJwt, userId: user.userId } ...

The React application deployed on Heroku is experiencing difficulties when trying to send a POST request

While experimenting with the Chatkit API, I encountered an issue when deploying a React app to Heroku. Everything worked perfectly on my local machine, but upon pushing it to Heroku, I started receiving errors such as "Failed to load resource: net::ERR_CON ...

Implementing Angular *ngFor to Reference an Object Using Its Key

myjson is a collection of various hijabs and headscarves: [ { "support": 2, "items": [ [ { "title": "Segitiga Wolfis", "price": 23000, "descripti ...

Having trouble getting Node.js, express, socket.io, and ejs to work together?

Currently, I am working on improving my knowledge of java-script and had the idea to create a basic chat app using Express, stock.io, and ejs. Unfortunately, I am facing some challenges in getting it up and running smoothly. Below is the snippet from my ...

Mocha tests abruptly end with the error message: Unable to locate module 'pg-native'

Unexpectedly, our mocha tests come to a halt and display the following message on the console: Cannot find module `pg-native` No stack trace is provided, and mocha fails to render the usual test output. The test abruptly terminates. If I deactivate the ...

Experiencing unexpected 502 Bad Gateway errors from AWS API Gateway following an update to Lambda runtime from Node 8.x to Node 12.x

After transitioning our staging environment for the REST API from NodeJS 8.x to NodeJS 12.x on AWS Lambda due to end of life for NodeJS 8.x runtime, we have encountered a new issue. Periodically, requests from our frontend web app to API Gateway fail with ...

passport.authenticate method fails due to empty username and password values

I seem to be making a simple mistake while following a tutorial. Even though I believe I have followed all the steps correctly, when I submit the login form, I get redirected to the "failureRedirect" page. When I checked the source code in the passport mod ...

Issue with Node.js local web server: unable to locate module ws despite it being installed globally

I am trying to set up a simple local web server for development purposes on my Windows 7 machine. Following the installation of node.js, I ran the command: npm install -g local-web-server Afterwards, I navigated to the directory D:\[path_to_webconte ...

NodeJS and ExpressJS fail to redirect to the main landing page

I am currently developing a shopping cart application using nodejs/expressjs. I have encountered an issue with redirecting back to the homepage ('/') after the user submits their credentials during sign up. Despite my search for relevant articles ...

Leveraging Node.js to copy files, checking for missing files through the utilization of fs.readdir, and

During my attempt to copy a large number of files within a folder using "ncp", I've encountered an issue where not all the files are successfully copied. After checking, it seems that some files are consistently missing. I resorted to using fs.readdi ...

Support control characters when using util.inspect or console.log

Having trouble with a callback error: return cb({code, message: `The command could not be executed: "${chalk.bold(cmd)}".`}, result); The error is being handled like this: if (err) { console.error(err); process.exit(1); } Resulting in control ch ...

Troubleshooting Problems with Node JS Express, Passport JS, and Authentication on Android Devices

I am currently setting up a login system using Node JS Express and Passport, incorporating Passport's local strategy: . The database in use is MongoDB. An issue I'm facing is the inconsistency of successful logins (especially with 'User A&ap ...

Authentication Error: PassportJS Method not Found

Encountering a problem while trying to access passport functions from a separate config file. It seems like passport is not exposed when the file is required in routes. The error occurs at .post(passportConfig.authenticate('local-login', { Error ...

Can you explain the concept of a framework operating "on top of" node.js in a way that would be easy for a beginner to understand?

If someone is new to JavaScript, how would you explain the concept of "on top of node.js" in simple programming language? I am looking for a general explanation as well as specific reference to Express on top of node.js in the MEAN stack. Appreciate your ...