What is express?
Express is a simple and flexible node.js web application framework, which provides a series of powerful features to help you create various web applications, and rich HTTP tools. Express does not re-abstract the existing features of node.js, but only extends the functions required by web applications on top of it.
1. The use of express
- Create service
var server=express(); - Listen
server.listen(8080); - Process the request
server.use('address', function(req,res){})
The req and res here are not the original req and res. The functions of the original req and res are still retained in express, but some new content will be added.
For example: the first parameter in native res.write() can only be a string or buffer binary object, but res.send() under the express framework can accept json.
2. Data Analysis
There are three ways to process data
server.get(directory, function(req,res){}); ------>processing get
server.post(directory, function(req,res){}); --- --->Process post
server.use(directory,function(req,res){}); ------>Can handle both get and post
- handle get
server.use('/',function(req,res){
console.log(req.query);
});
- process post
const bodyParser=require('body-parser');
server.use(bodyParser.urlencoded({
}));
//注意这里的urlencoded提供两个参数:
//extended:true/false; ------->扩展模式
//limit:2*1024*1024 ------->限制post的规模
server.use('/',function(req,res){
console.log(req.body);
});
- Chain operation ------>next()
next() indicates the next action
const express=require('express');
const bodyParser=require('body-parser');
var server=express();
server.listen(8080);
server.use('/',function(req,res,next){
console.log('a');
//next();
})
server.use('/',function(req,res,next){
console.log('b');
})
//如果没有next()语句,结果为a
//如果有next()语句,结果为a b
- Write a middleware body-parser for post processing
//在www目录下写一个middle.js
const querystring=require('querystring');
module.exports=function(req,res,next){
var str='';
req.on('data',function(data){
str+=data;
});
req.on('end',function(){
req.body=querystring.parse(str);
//把字符串变为json
next();
})
};
//在www目录下写一个server.js
const express=require('express');
const bodyParser=require('./middle.js');
var server=express();
server.use(bodyParser);
server.use('/',function(req,res){
console.log(req.body);
})
server.listen(8080);
3. cookie and session
The http protocol has a natural deficiency ------> stateless, the server cannot identify whether it is the same person between two requests.
cookie: Save some data in the browser and bring it with each request. Not safe, limited (4k).
session: Save data on the server side. Safe, unlimited. Session is implemented based on cookie. There is a session ID in the cookie, and the server uses the session ID to find the session file to read and write.
Hidden danger: sessionid:session hijacking
(1) Related to cookies
1>. Send cookie
res.cookie(名字,值,{
path:'/',maxAge:...(单位:ms)});
Path represents the directory in which cookies can be read
2> read cookies
using middleware: cookie-parser
const cookieParser=require('cookie-parser');
server.use(cookieParser('秘钥'));
3>Delete cookies
server.use('/',function(req,res){
res.clearCookie('user');
});
(2) How to realize the encryption of cookies?
Method 1: signature
req.secret='secret key';
res.cookie(name,value,{signed:true});
//举个例子:
req.secret='aabbccddeeff';
res.cookie('user','blue',{
signed:true});
console.log(req.signedCookies);------>签名的cookie
console.log(req.cookies); ------>未签名的cookie
Method 2: cookie-encrypter middleware
(3) Cookie exercise
const express=require('express');
const cookieParser=require('cookie-parser');
var server=express();
server.use(cookieParser('bbccddeeffss'));
server.use('/',function(req,res){
res.cookie('user','blue',{
path:'/aaa',maxAge:30*24*3600*1000,signed:true});
res.send('ok');
console.log(req.url);
console.log(req.signedCookies);
res.end();
});
server.listen(8080);
result:
(4) session
The session exists on the server side. Since the session cannot exist independently,
you must first use server.use(cookieParser()); then use server.use(cookieSession());
middleware: cookie-session.
When we use a variable use cookie-session middleware.
Because of session hijacking, cookie-session must have a secret key.
1> get session
server.use(cookieSession(){
name:...,
keys:[.,...,...],
maxAge:.....
});
2> process session
server.use('/',function(req,res){
req.session['count']=.......;
});
3> delete session
delete req.session
(5)session exercises
const express=require('express');
const cookieParser=require('cookie-parser');
const cookieSession=require('cookie-session');
var server=express();
//keys循环取100000个,加大破译难度
var arr=[];
for(var i=0;i<100000;++i){
arr.push('sign_'+Math.random());
}
server.use(cookieParser());
server.use(cookieSession({
keys:arr,
name:'sess',
maxAge:2*3600*1000,
//99*24*3600*1000 ----->maxAge近似取无限的方式
}));
server.use('/',function(req,res){
if(req.session['count']==null){
req.session['count']=1;
}else{
req.session['count']++;
}
console.log(req.session['count']);
res.send('ok');
});
server.listen(8080);
4. Template engine
- jade: destructive, intrusive, strong dependency
- Features: a. Specify the level according to indentation
b. Can identify single and double tags (all custom tags are double tags)
(1). Render the jade file to the server
//www目录下的1.jade
html
head
style
body
div
div
div
//根目录下的serverJade.js
const jade=require('jade');
var str=jade.renderFile('./www/1.jade',{
pretty:true});
console.log(str);
(2) Add attributes in the jade template file.
Attributes are placed in () and separated by English commas
//www下的1.jade
html
head
style
script(src="try.js")
body
div
div
div
(3) Add content
Jade is a smart engine, because a is a row-level element, so even if there is a pretty:true beautification format, the printed str has no spaces.
a(href="https://www.baidu.com") 官网
(4) Content and label nesting
For example, want to achieve:
//html为
<div>
29
<span>33</span>
</div>
//jade应写成
div 29
span 33
(5) Special style and class
style attributes:
a. As ordinary attributes
div(style="width:200px;height:200px;color:red;")
b. as a jason
div(style={
width:'200px',height:'200px',color:'red'})
class attribute:
a. As a normal attribute
div(class="left-wrap color")
b. as an array
div(class=['left-wrap','color'])
(6) Shorthand for attributes
//属性简写
div.box
div#both
//将div中的属性变成json传递
div(title='myfirst',id='one')
div&attributes({
title:'myfirst',id:'one'})
(7) '|' means output as it is
html
head
body
|aaa
'.' means that all the next-level content inside is output as it is
script.
function main(){
var div=getElementsByTageName('div')[0];
div.innerText='this is a fine day';
};
main();
'include ...(filename)'
//1.js
function main(){
var div=getElementsByTageName('div')[0];
div.innerText='this is a fine day';
};
main();
//1.jade
script
include 1.js
(8) Using variables
//www下的3.jade
html
head
body
div 我的名字:#{
name}
//serverJade.js
const jade=require('jade');
var str=jade.renderFile('./www/3.jade',{
pretty:true,name:'blue'});
console.log(str);
(9) Write js code
'-' in jade to indicate that this section is code
//3.jade
-var a=10;
-var b=9;
div value为#{
a+b}
write loop in jade
//www下的4.jade
-for(var i=0;i<arr.length;++i)
div=arr[i]
//serverJade.js
const jade=require('jade');
var str=jade.renderFile('./www/4.jade',{
pretty:true,
arr:['aaa','bbb','ccc','ddd','eee']
})
console.log(str);
Writing switch-case in jade
becomes case-when here
//4.jade
-var a=3
case a
when 0
div aaa
when 1
div bbb
when 2
div ccc
default
div ddd
(10) Tags in js attributes
In order to avoid hidden dangers to website security, (injection attack) jade will automatically eliminate the tags in the attributes passed by js.
'!' means not to eliminate the label in the attribute passed by js
//4.jade
div!=content
//serverJade.js
const jade=require('jade');
var str=jade.renderFile('./www/4.jade',{
pretty:true,
arr:['aaa','bbb','ccc','ddd','eee'],
content:'你好呀<p>今天天气真好</p>花也漂亮<span><span>'
})
console.log(str);
(11) jade small exercises
//5.jade
doctype
html
head
meta(charset='utf-8')
title jade测试
style.
div{
width:30px;
height:30px;
background-color:gray;
float:left;
color:white;
line-height:30px;
text-align:center;
margin:1px;
}
.last{
clear:left;
}
body
-var i=0;
-while(i<12)
if i%4==0&&i!=0
div.last=i++
else
div=i++
//serverJade.js
const jade=require('jade');
const fs=require('fs');
var str=jade.renderFile('./www/5.jade',{
pretty:true});
fs.writeFile('./build/index.html',str,function(err){
if(err){
console.log('编译失败');
}else{
console.log('成功');
}
})
result: