Tips for transferring data from Express to .ejs file during redirection in Node.js

When I submit the login form in my login.ejs file, the page redirects if the details are correct. If the password is wrong, however, I want to display a message in the .ejs file indicating this. Below are the details:

Here is the code in my app.js file - I am sending a JSON object and hiding the invalid password message in the .ejs file.

 app.get('/', function (req, res) {

     res.render("login",{Error:"none"});

});

app.post('/login', function (req, res) {

    var username = req.body.username;
    var password = req.body.password;
     //Code here to check if details are correct or not
     res.redirect('/',{Error:'block'});
}

Here is my login.ejs file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8>
    <title></title>
    <link rel="stylesheet" href="css/style.css" type="text/css" />
    <link rel="stylesheet" href="css/font.css" type="text/css" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>
    <div class="Error" id="error" style="display:<%=Error%>;">Invalid email/phone or password</div>
    <div class="Body">
        <form class="LogBox" action="/login" method="post">
            <div class="Head">Log In</div>
                <input type="text" placeholder="Email or Phone" class="inputfrontbutton" name="username">
                <input type="password" placeholder="Password"  class="inputfrontbutton" name="password">
                <input type="submit" value="Log In" class="frontsubmit">
        </form>
    </div>
</body>

</html>

I am having trouble sending JSON data in the redirect. Is there another way to achieve this?

Answer №1

As mentioned in the documentation for the .redirect method on ExpressJS website:

The syntax for res.redirect is as follows:

res.redirect([status,] path)

This function redirects to a URL based on the specified path and status code. If no status is provided, it defaults to "302 Found".

It's important to note that attempting to call the method like this won't work:

res.redirect('/',{Error:'block'});

Even if this were to work, it would simply redirect to the '/' route, triggering the initial login page without displaying the error message.

A better approach would be to modify the last line of the

app.post('/login', function (req, res) {...}
to

res.render("login",{Error:"block"});

Answer №2

If you're utilizing AJAX, it's not possible to perform a redirection following an AJAX call. Instead, opt for using the 'send' function.

res.send({Error:'block'});

Answer №3

If you want to pass json using the res.render method, you can do so easily. However, if you need to use the res.redirect method, you can follow these steps.

  1. To pass data with res.redirect, you can use encodeURIComponent.
    app.get('/user', function(req, res) {
    var error = encodeURIComponent('error');
    res.redirect('/?user=' + error);
    });
  2. Another option is to use session management. Check out this resource for setting up sessions: Link to setup Sessions
    req.session['error'] = "Error";
    req.redirect('/');
  3. You can also utilize express-flash to display errors on the page. Here's a basic example and usage guide: Basic example an Usage of express-flash

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

Set a variable equal to the output of an external function, but receive an undefined value in

I've been facing an issue where I'm trying to store the value of an external function in a JavaScript variable, but it keeps returning undefined. The external function in question is designed to search for a specific record within a database: f ...

DataTables.js, the powerful JavaScript library for creating interactive tables, and its compatible counterpart

I'm currently making some changes to a dynamic table that require enabling a vertical scroll bar. As a result, I need to implement this vertical scroll bar mechanism on an existing table. The code in our project utilizes dataTables.js version 1.5.2 ...

How to adjust the Timezone of a JavaScript Date without affecting the designated time?

var schedule = { start_at = Date ( '2017-10-10' ), // Data is not editable - ORM will provide ... }; // Mon Oct 09 2017 20:00:00 GMT-0400 (Eastern Daylight Time) console.log ( schedule.start_at ); Seeking a way to adjust the time of an ...

Discovering the most recently selected element in jQuery

Currently reading a jQuery tutorial from the Head First series and practicing with an example where I need to identify the last selected element. In Chapter 2, there is a task involving four images on a page. When a user clicks on any of these images, the ...

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...

Enable users to designate custom methods as either asynchronous or synchronous

These are my TypeScript method signatures: onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; async onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; onPinnedUnhandledRejection?(info: HavenInfo, ...

Sockets causing a blockage in the Express server

Encountering an issue while setting up an express server with Sockets (using the socketcluster-server module). After sending around 20 http requests, the express server gets blocked, leading to the Sockets (client) reporting a connection depletion. Has an ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

What is the proper way to configure the checklist-model directive in my AngularJS application?

I'm new to the node.js/grunt world, so please bear with me if my question seems basic... I have an angular.js project set up with yeoman/grunt, and now I want to add a directive, specifically this one. However, I'm unsure of how to install it! ...

Tips for sending a parameter to a URL from a controller using AngularJS

I am currently working on a feature where I need to combine adding and editing functionalities on one page. The items are listed in a table below, and when the edit button is clicked, I want to pass the ID of that specific item in the URL. This way, if the ...

Contrary to GraphQLNonNull

I am currently working on implementing GraphQL and I have encountered a problem. Here is an example of the code I wrote for GraphQL: export const menuItemDataType = new GraphQL.GraphQLObjectType({ name: 'MenuItemData', fields: () => ...

What is the reason behind npm's decision to categorize dependencies into two separate categories?

Within your package.json, you will find the sections for dependencies and devDependencies. { "devDependencies": { "webpack": "^4.42.1" }, "dependencies": { "react": "^16.13.1" } } The purpose behind this division is clear: dependencies ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...

Steps for transitioning a VUE JS project to TypeScript

Is it possible to transition a VUE JS project from JavaScript to TypeScript without rewriting everything? I heard from a friend that it can be done through the VUE CLI, but I haven't been able to find any documentation or articles on this method. Has ...

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...

What is preventing me from accessing the $sceProvider?

Struggling to implement a filter using $sceProvider to decode HTML tags. Here's my current code structure: myApp.filter('decodeHtml', function($sce) { return function(item) { return $sce.trustAsHtml(item); }; However, upon integrating ...

dynamic jquery checkbox limit

I am working with the following HTML code: <input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1 <input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2 &l ...

NodeJS Password Recovery

Recently, I implemented a password reset feature using NodeJS/Passport. I found an excellent guide: . I followed the instructions and it was mostly successful. However, there seems to be a critical error that I can't locate. When a user goes through t ...

"PHP script for submitting a form with a post button

Can anyone help me figure out why the submit function isn't working? I've been trying to solve the problem with no luck so far. Any ideas on what might be causing this issue? <?php if(isset($_POST['submit'])){ echo ("Submit fun ...

Vuetify's v-text-field not properly aligning text to the center

The alignment of the text in v-text-field is causing issues for me, as I am unable to center it. Despite attempting various solutions, I have not been successful. 1. <v-text-field type="number" class="mr-2 text-center"></v-te ...