What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not be redirected elsewhere. Should I consider changing the type of the logout button to submit?

Here is the HTML code snippet:

<body>
    <p id="after"><%= username %></p>
    <div class="login">
      <h1>Login</h1>
      <form action="/" method="post">
        <label for="username">
          <i class="fas fa-user"></i>
        </label>
        <input type="text" name="username" placeholder="Username" required />
        <label for="password">
          <i class="fas fa-lock"></i>
        </label>
        <input
          type="password"
          name="password"
          placeholder="Password"
          id="password"
          required
        />
        <input type="submit" value="Login" />
        <button id="logout" name="logout" type="button">Logout</button>
      </form>

This is the JS CODE section:

 app.get("/", function (req, res) {
  const username = req.flash("user");
  res.render("login", { username });
});

app.post("/", function (request, response) {
  // Capture the input fields

  let username = request.body.username;
  let password = request.body.password;
  // Ensure the input fields exists and are not empty
  if (username && password) {
    // Execute SQL query that'll select the account from the database based on the specified username and password
    connection.query(
      "SELECT * FROM accounts WHERE username = ? AND password = ?",
      [username, password],
      function (error, results, fields, name) {
        // If there is an issue with the query, output the error
        if (error) throw error;
        // If the account exists
        if (results.length > 0) {
          
          request.session.loggedin = true;
          request.session.username = username;

        

          request.flash("user", request.body.username);

          response.redirect("/");
        } else {
          response.send("Incorrect Username and/or Password!");
        }
        response.end();
      }
    );
  } else {
    response.send("Please enter Username and Password!");
    response.end();
  }
    //try to logout
  app.get("/", async (request, response) => {
    if (request.flash.username) {
      delete request.flash.username;
      response.json({ result: "SUCCESS" });
    } else {
      response.json({ result: "ERROR", message: "baba" });
    }
  });
});

app.listen(port);
console.log(`Server is listening on port ${port}`);

Answer №1

To ensure the message is removed from req before displaying the page, you can use the following code snippet:
const myUser=flash("usrID","username");
......
flash("usrID","");
and then verify it on the frontend. For instance, if you are using EJS:

 <% if ( myUser.length!==0 ) { %> //other condition is needed
    .............
    .............              
 <% } %>

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

Play framework fails to apply style attributes correctly

When working with play-framework 2.3.x, I am in the process of creating a form and would like to show/hide it based on a model attribute. Typically, setting the style attribute manually using style = "display: none" and style = "display: block" works fine. ...

Steps to avoid IE11 prompt (Do you really want to leave this site)

In the midst of making a webpage, I find myself faced with the peculiar issue of only having a dropdown to select. To make matters worse, when attempting to navigate to the next page in IE11, a pesky message pops up. Curious about the default behavior of ...

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

JavaScript: a highly effective method for verifying if a variable is a function, an array, or an object

Imagine a scenario where we have a variable that could potentially be a function, object, or array. I am in search of the most efficient method to determine its type. In my opinion, the current approach is not optimized because if I already know that isF ...

What is the process for fetching the chosen outcome from a subsequent webpage using HTML?

How can I display selected cities on a different webpage after clicking a button? Currently, I can only get the results on the same page. For example, if a user selects NYC and Delhi, those cities should be displayed on another HTML page. ...

Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div: <div class="row" ng-app="myApp" ng-controller="myC ...

The keyup event fails to trigger for the search input in datatables when ajax is being used

When loading a page with a jQuery datatable via AJAX, I am aiming to implement custom filtering when the user starts typing in the default filter provided by datatables. The custom logic needs to be applied when the keyup event is triggered. Since AJAX is ...

What is the best way to specify the stream responseType for my client?

Is there a way to download a file from my express js app using AJAX instead of server-side handling? const response = await Axios({ method: 'GET', url: url, responseType: 'stream' }) Instead of piping the data directly to ...

Tips for developing integration tests for medium-sized nodejs applications with heavy reliance on 3rd party APIs

I am the owner of a medium-sized nodejs application that can be found on GitHub under the link here. This application heavily relies on various 3rd party APIs to function. Essentially, the purpose of this app is to make calls to different Salesforce APIs, ...

Ways to Resolve Issues with WordPress Update and Publish Failures

It has been quite some time since Gutenberg was introduced to us, and it seems like we all have a complicated relationship with it. Navigating the Block editor to create a post or page can be challenging, especially when it used to be so simple. But what& ...

Click here to start your Django download now

I am looking for a way to monitor the number of times a file has been downloaded. Here is my plan: 1) Instead of using <a href="{{ file.url }}" download>...</a>, I propose redirecting the user to a download view with a link like <a href="do ...

The dimensions of the window - creating divs within td elements - the appearance of scroll

Here is the HTML code that I am working with: <table> <tr> <td class='tclone' id='clone'></td> <td class='loader' id='loader'> <div id='tdiv& ...

What is the best way to retrieve widget options when inside an event?

Creating a custom jQuery widget: jQuery.widget("ui.test",{ _init: function(){ $(this.element).click(this.showPoint); }, showPoint: function(E){ E.stopPropagation(); alert(this.options.dir); } } Initializing the cu ...

Angular JS form cloning feature

I'm facing a challenge in creating a dynamic form with multiple sections. At the end of the form, I want to include a "Add New Form" button which will duplicate the existing form below it, each with its own save button. What's the most effective ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...

Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive. For example, if I scroll down twice, the ...

In Internet Explorer, when utilizing a table-cell with a variable height, the position should be set to absolute for

I'm struggling with getting a uniform height in my horizontal layout using display: table-cell. While it looks great in Chrome, I can't seem to get Internet Explorer to display it the same way. Check out this link for reference This is how I wa ...

Transferring information from the router to the server file using Node.js and Express

I am in the process of creating a web application using node.js, and I need to transfer data from my router file, which handles form processing, to my server file responsible for emitting events to other connected users. router.js module.exports=function ...

Refreshing webpage content by utilizing iframes

I am looking for a way to completely clear a webpage using either Javascript or PHP. However, there seems to be an issue with a specific area of the page that is marked as: data-form="manual iframe" When attempting to clear the page, only the data within ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...