javascript – Show data from nodejs to html-ThrowExceptions

Exception or error:

I have a nodejs project that login in a page and show result in other page using expressjs.

This is my login.ejs:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <body>
        <form method="POST" action="/login">
            <label id="empID">Enter your name:</label>
            <input name="empID" id="empID" type="text">
            <input type="submit" value="Check">
        </form>
    </body>
</html>

and this is index.js:

var express = require("express");
var bodyParser = require ('body-parser');
var app = express();

app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.set("view engine", "ejs");
app.set("views", "./views");
app.listen(3000);

app.get("/login", function(request, res)  {
    res.render("login");
});
app.post("/login", function(request, response){
    console.log(request.body);
    var empID=request.body.empID;
    console.log(empID);
    if (empID=="hello") {
       result="John";}
    else {
       result="Alexa";}
});

and the target page is question.ejs:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <div class="question-form">
        <header>
            Your name is...???
        </header>
    </div>
</html>

How can I send my result to question.ejs (For example the result in question page: Your name is John when I submit “hello” in login page) after I fill in the empID input and submit Check button. Thank you so much!

How to solve:

You can render the question page like following.

res.render('question', { name: result });

And change question.ejs to read the name.

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <div class="question-form">
        <header>
            Your name is <% name %>
        </header>
    </div>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *