reviews - The demo is to demonstrate passing data to ejs
app12.js is the data provider. There are two pieces of data - a string and an array.
default12.ejs is to present the data, using javascript language and code block and expression block.
lab 21: folder public - reference it
under app folder, create a subfolder, css
add a css file, hello.css
create the app file, app13.js
create a ejs file, default13.ejs
launch the server, see the result in the browser.
// public/css/hello.css
body {
background-color: lightgray
}
// in app13.js, add one line and modify method render
app.use(express.static('public')
app.get(.. {
res.render(default13.ejs)
}
// default13.ejs
review
When referencing the css, folder public is not needed to specify. css/hello.css will be enough.
The static is a express build-in middleware.
When a web request arrives the severs, all the middleware will be executed in sequence.
lab 22: folder public - html file, route
In this demo, a html file is returned.
Two things are needed method sendFile, which requires absolute path.
When testing in a browser, type localhost:3000/greeting
3.1 send json data to nodejs app, using client tool - ARC
This is to review the 7-nodejs in this site. The section is rest post
ARC is used to prepare the posting data,ncluding the following:
url
set http method to post
data
Data can be used for auth -userid, password.
It can be used as the database table key content.
others
app.post method in the app js is used for the handler
Parsing data from web network to express app data
Package body-parser is needed. It is a middleware.
Its json method is used to pared for json data.
3.2 send HTML form data to nodejs app
Refer this site, 07 nodejs, Posting data with HTML form
In the html form tag, the method is Post
lab 41: create the app skeleton for post route, test with a client tool
create a folder for the app. Then create 2 subfolders, public, views
add its app file as below
make suter express and ejs are installed.
launch the service
open the chome ARC, client tool
url: localhost:3000/lab41
method: post
Content-type: application/json
payload: {"name": "Emi"}
click button send
You'll see the response at the bottom of ARC.
// application javascript
var express = require('express')
var app = express();
app.use(express.static('public')
app.set('view engine', 'ejs');
app.post('/lab41', function(req, res){
res.end('post completed, 5:00 pm')
})
var server = app.listen(3000, function(){
console.log("Listening on port 3000, test 5:00 pm");
})
lab 42: post route - get a html form, post form data, get a page back
Two ejs files are used.
The first is for html form.
the second is the page returned after a posting.
The reason to use ejs because of passing data.
In folder views,create two html form pages, form.ejs, echo.ejs.
create 3 new files -app43.js, form43.ejs, echo43.ejs
test to see the html select choice for fruit.
// form43.ejs cloned from form42.ejs, adding the following code
Most Favor Fruit:
// echo43.ejs just cloned from echo42.ejs...
// app43.js cloned app42.js, modifying the get route
app.get('/lab43',function(req, res){
res.render('form43', {myFruits:['apple', 'banana', 'melon', 'orange']})
})
lab 44: convert the url data from network to the app format in memory
// app43.js, add the following code
...
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended:false}))
app.post('/lab43', function(req, res){
console.log("enter location post for lab43, 7:20 am")
var fn = req.body.firstname // application specific
var ln = req.body.lastname
var fruit = req.body.fruit
console.log('data = ' + fn + ' , ' + ln + ' , ' + fruit)
res.render("echo43")
})
package body-parser is needed, install it, npm install body-parser -save
It is a middleware.
Its method urlencoded is used.
When the post request reaches the service, the middleware's method, parses the data, save in the req object, then go to the next.
console.log verifies the result.
What you want to do with the post data
for auth
for database table access with the data for filtering...
There are two ways to response
returning a html page back
Using ajax to post, return some data.
lab 45: ehco the posting data in a html page
create form45.ejs, echo45.ejs, app45.js, cloned from previous ones(43).
In all 3, change the route from lab43 to lab45.
modify others as below.
launch the server, node app45
launch the browser, localhost:3000/lab45
// app45.js
app.post('/lab45', function(req, res){
console.log("enter location post for lab45, 8:05 am")
var fn = req.body.firstname
…...
var gender = "male"
res.render("echo45",{"name": fn, "sex": gender})
})
// echo45.ejs
name is <%= name %>
sex is <%= sex %>
reviews
in the route handler, data male may be retrieved from a database table access, with name data.
in the route handler, res.render includes a argument for data.
The json key names, name and sex is used in echo45.ejs
The related mechanism is as below:
In app45.js, a json is passed as argument.
A ejs file includes two parts - static HTML rendering code, and js blocks for dynamic data. It is like using a template.
Then,the ejs engine resolves the js code blocks into html code...
A html page is created in the server, and send back to the http client to replace the old page.
lab 51: asynchonously get data
This demo is to get data asynchronouly from the same web site.
Ejs is not used here for focus. A html client is used.
jQuery is used for convenience.
Ajax, SPA style
step 1: prepare the app with package express, path, and public folder.
step 2: under public folder, create a subfolder html, create a html file ajaxGet.html.
step 3: in the app js file, add the route get for data.
step 4: code the html file as below
step 5: in the app js file, add the route get for a html client.
step 6: open my terminal window, enter node app5.js
step 7: open the browser,enter localhost:3000/lab5get
step 8: The html page shows up. Click button ajax get. You'll see the data return from the data service.
My dog is Tairo. He is a brown dog.
// app5.js
prepare the route for json data service
app.get('/data5', function(req, res){
console.log("enter data5")
var jsonDog = {"name": "Tairo", "color": "brown"}
res.json(jsonDog)
})
prepare the route for a HTML client
app.get('/lab5get', function(req, res){
res.sendFile(path.join(__dirname + '/public/html/ajaxGet.html'))
})
// public/html/ajaxGet.html
lab 52: asynchonously post data
This demo is to post data asynchronouly from the same web site.
step 1: prepare the app with package express, path, and public folder.
Package body-parse is needed to parse posting data.
step 2: under public folder, create a subfolder html, create a html file ajaxPost.html.
in html body tag, code the html elements for data input
in html head tag, code
Retrive data from the input elements, prepare a json data in string for network
Post the data, in the callback, update the same page
code app52.js
route name: lab52post
in get method, response with a html file.
Middleware body-parser will convert the data from network format to app variables
in post method
Using req.body's data to format a msg.
response it to the same page for update in a callback.
// in ajaxPost.html A htm form is not used.
5.2 ajaxPost.html
test 7:32 am
dog name:
dog color:
// in ajaxPost.html - head tag jquery is needed
$(document).ready(function(){
$("#btn").click(function(){
alert("test ajax post, test 11:22 am");
var name = document.getElementById('dogname').value
var color = document.getElementById('dogcolor').value
var myJson = {dogname: name, dogcolor: color}
var strJson = JSON.stringify(myJson)
alert("strJson = " + strJson)
$.ajax({
url: '/lab52post',
type: 'POST',
contentType: 'application/json',
//data: JSON.stringify({dogname: 'Tairo',color: "brown"}),
data: strJson,
success: function(response){
alert('the post is OK ' + response)
$("#myDog").append(response)
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
});
// app52.js
...
var bodyParser = require('body-parser')
app.use(bodyParser.json())
....
app.get('/lab52post', function(req, res){
res.sendFile(path.join(__dirname + '/public/html/ajaxPost.html'))
})
app.post('/lab52post', function(req, res){
var p1 = req.body.dogname
var p2 = req.body.dogcolor
var p3 = 'Peter' // It can be from db access with dog name
var msg = p1 + ' is a ' + p2 + ' dog. The owner is ' + p3
console.log(msg)
res.end(msg)
})