I just started to learn node.js today and I'm trying to render post data and raw html using EJS template engine.
I am trying to render the post data and raw html depending on the if else if statement in stats.
I'm not sure if this could be done so i was hoping maybe someone could tell me if it can be?
app.js:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
app.set('view engine', 'ejs');
app.get("/", (req, res) => {
res.render(__dirname + "/views/index");
});
app.post('/stats', (req, res) => {
var first_name = req.body.firstname;
var last_name = req.body.lastname;
if (!first_name) {
var html_code = "<b>You didn't add a first name</b>";
res.render(__dirname + "/views/stats", {
htmlcode: html_code
});
} else if (!last_name) {
var html_code = "<b>You didn't add a last name</b>";
res.render(__dirname + "/views/stats", {
htmlcode: html_code
});
} else if (first_name && last_name) {
var html_code = "<b>First name is </b><%= first_name %> <br> <b>Last name is </b><%= last_name %>";
res.render(__dirname + "/views/stats", {
htmlcode: html_code,
firstname: first_name,
lastname: last_name
});
}
});
const listener = app.listen(process.env.PORT, () => {
console.log("Your app is listening on port " + listener.address().port);
});
views/index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send Stats</title>
</head>
<body>
<form action="https://server.com/stats" method="POST">
firstname: <input type="text" name="firstname" /><br/>
lastname: <input type="text" name="lastname" /><br/>
<button type="submit">Send</button>
</form>
</body>
</html>
views/stats.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>name stats</title>
</head>
<body>
<div><%= htmlcode %></div>
</body>
</html>
output:
<b>First name is </b><%= first_name %> <br> <b>Last name is </b><%= last_name %>