0

I am new to node js. i am trying to learn node js. My question is how can we create dynamic webpages using node js?

PHP

<html>
<body>
    <?php .......... ?>
</body>

Like in php we can do this way. How can we do in node js.

3

2 Answers 2

7

First off you would start by installing the nodejs framework expressJS

sudo npm install express

For instance, let's say you want to create a form.

<html>
<body>
<head>
This is a simple form
</head>
<body>
<form action="/" method="POST">
<label for="firstName">First Name:</label>
<input name="firstName">
<br>
<label for="lastName">Last Name:</label>
<input name="lastName">
<br>
<button type="submit">send</button>

This what the server side part would look like

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

var urlencodedParser = bodyParser.urlencoded({ extended: false});

// Set EJS View Engine**
app.set('view engine','ejs');
// Set HTML engine**
app.engine('html', require('ejs').renderFile);
//set directory
app.set('views', __dirname + '/views');
//static folder
app.use(express.static('staticfolder'));


app.get('/form', function(req, res) {
    //open form.html from the views directory
    res.render('form');
});

app.post('/', urlencodedParser, function(req, res) {
    //retrieve first and lastname
    var firstName = req.body.firstName;
    var lastName = req.body.lastName;
    //open submitted.html after the user has submitted the form
    res.render('submitted', {output: req.body.firstName});
});

app.listen(3000);

Page that will be displayed when user submits the form. It is called submitted.html in this case

<html>
<body>

<p> you have submitted the form </p>
<!--firstname entered by user-->
<p> your first name is <%= output %></p>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

0

You need a template to dynamically change its content. Step 1: Create a server with Express Node.JS Framework. Step 2: Use EJS(Embedded JavaScript) to create a template. Follow the instructions bellow: https://shockoe.com/ideas/development/creating-dynamic-web-pages-ejs/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.