当前位置:网站首页>Express framework knowledge - Art template template, cookie, session
Express framework knowledge - Art template template, cookie, session
2022-06-13 04:29:00 【Radix notoginseng and small sugar】
Express frame
Set up a server
const express = require('express')
const app = express();
app.get('/',(request,respone)=>{
respone.end('hello express!!')
})
app.listen(3000,() => {
console.log('Express web server is listen at 3000 port!');
})

obtain post、get Request parameters
obtain get Parameters , It's through request.query
obtain post Parameters , Use
const app = express()
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
const express = require('express')
const path = require('path')
const fs = require('fs');
const app = express();
app.use(express.urlencoded({
extended: false }))
app.use(express.json())
app.get('/register',(request,respone)=>{
let filepath = path.join(__dirname,'register.html')
let content = fs.readFileSync(filepath,'utf-8')
respone.send(content)
// console.log(request.query);
})
app.get('/',(request,respone)=>{
respone.end('hello express!!')
})
app.post('/register',(request,respone) => {
let {
username,email,password,repassword} = request.body
})
app.listen(3000,() => {
console.log('Express web server is listen at 3000 port!');
})
Get static resources
Create a folder at the root of the project public As the root , stay pubilc Created in image Folder , Put static resources in the folder
Write... In the backend file app.use(express.static(path.join(__dirname,'public')))

Turn on the server , Input http://localhost:3000/image/1.png


You can get the path of static resources , On the front end html Of img Tag write <img src="/image/1.png" alt="">
It can be displayed on the page
art-template Templates
It can replace the above method of opening files .
// These four lines of code , The initialization of the template engine
// introduce express-art-template, Use the corresponding engine
app.engine('html', require('express-art-template'));
// Project environment settings :
// Production environment ( on-line ) production
// development environment development
app.set('view options', {
debug: process.env.NODE_ENV !== 'production'
});
// Set the directory in which to find template files
app.set('views', path.join(__dirname, 'views'));
// Set the suffix of the template to html
app.set('view engine', 'html');
app.get('/register',(request,respone)=>{
respone.render('register')// Core code
})
art-template Template transfer data
// Server code
app.get('/register',(request,respone)=>{
let data = {
num:1,num2:3,books:["《 Journey to the west 》","《 A dream of red mansions 》","《 Water margin 》","《 The romance of The Three Kingdoms 》"]};
respone.render('register',data)
})
<div>
<p>{
{num}}</p>
<p>{
{num2}}</p>
</div>
<ul>
{
{each books}}
<li>{
{$value}}</li>
{
{/each}}
</ul>
{
{if num > num2}}
<p>p Labels do not necessarily show </p>
{
{/if}}
Page effects :
Hook function before processing the request
In the server-side code :
function checklogin(req,res,next){
console.log(" Execute this before executing the code ");
next();
}
app.use(checklogin)

Get parameters of dynamic route
<h1>List page </h1>
<hr>
<ul>
<li><a href="/detali/1"> Journalism 1</a></li>
<li><a href="/detali/2"> Journalism 2</a></li>
<li><a href="/detali/3"> Journalism 3</a></li>
<li><a href="/detali/4"> Journalism 4</a></li>
</ul>
Server code :
app.get('/register',(request,respone)=>{
respone.render('register')
})
app.get('/detali/:id',(request,respone)=>{
console.log(request.params);
})
//{ id: '1' }
The syntax format inherited by the template
The child template inherits the parent template
<!-- The parent template -->
<h1>List page </h1>
<hr>
{
{block 'content'}}
<ul>
<li><a href="/detali"> Journalism 1</a></li>
<li><a href="/detali"> Journalism 2</a></li>
<li><a href="/detali"> Journalism 3</a></li>
<li><a href="/detali"> Journalism 4</a></li>
</ul>
{
{/block}}

<!-- Sub template -->
{
{extend './register.html'}}
{
{block 'content'}}
<p>detali page </p>
{
{/block}}

Template filter
const express = require('express')
const template = require('art-template')
const app = express();
template.defaults.imports.haha = function(value){
return value * 200
}
app.get('/register',(request,respone)=>{
let data = {
num:1
}
respone.render('register',data)
})
<h1>Register</h1>
{
{num | haha}}

cookie
Set up and get cookie
You need to install cookie-parser modular
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
app.get('/set_cookie',(request,response)=>{
response.cookie('name','node',{
maxAge:60000}) // Set up cookie The storage time of
response.cookie('age',11)// If it is not set, the session will be closed by default , Just destroy it
response.send(' Set up cookie Information ');
})
app.get('/get_cookie',(request,response)=>{
let name = request.cookies['name'];
let age = request.cookies['age'];
console.log(name);
console.log(age);
response.send(` Set up cookie The message is :${
name},${
age}`)
})
app.listen(3000,() => {
console.log('Express web server is listen at 3000 port!');
})


session
characteristic :
1、session Data is saved on the server side
2、session Is stored in the form of keys and values
3、session Depend on cookie, Every session The identification of the client corresponding to the information is saved in cookie in
Use :
First install and introduce :cookie-session
const cookieSession = require('cookie-session');
Sign up to app in :
app.use(cookieSession({
name:"my_session", //name by session name , Just start a string by yourself
keys:["$^%%&^&%$RT%&TYGSGSFRR554785432$#@$$#%[email protected]#%"],
// Internal encryption requires keys, keys For random strings
maxAge: 1000 * 60 * 60 * 24 // Expiration time
}))
Set up session:req.session[“name”] = "session_node"
obtain session:let name = req.session[“name”]
The complete code is as follows :
// 1、 Install first :yarn add cookie-session
// If you make a mistake , Add version number later , Then just keep returning yarn add [email protected]
// 2、 Set to app in
const cookieSession = require('cookie-session');
app.use(cookieSession({
name:"my_session", //name by session name , Just start a string by yourself
keys:["$^%%&^&%$RT%&TYGSGSFRR554785432$#@$$#%[email protected]#%"],
// Internal encryption requires keys, keys For random strings
maxAge: 1000 * 60 * 60 * 24 // Expiration time
}))
app.get("/setSession",(req,res)=>{
// Set up session
req.session["name"] = "session_node"
req.session["age"] = 11
res.send(" Set up Session")
})
app.get("/getSession",(req,res)=>{
// obtain session Information
let name = req.session["name"]
let age = req.session["age"]
res.send(` obtain Session, ${
name}, ${
age}`);
})

边栏推荐
- MCU: EEPROM multi byte read / write operation sequence
- [chapter 67 of the flutter problem series] the solution to the problem that the get plug-in cannot jump to the route twice in the dialog pop-up window in flutter
- SQL 进阶挑战(1 - 5)
- How to use debounce in lodash to realize anti shake
- knife4j aggregation 2.0.9支持路由文档自动刷新
- Redis主从复制、哨兵模式、集群
- Online audio adjustment technology summary
- 【LeetCode】860. Change with lemonade (2 brushes for wrong questions)
- Use ASE encryption and decryption cache encapsulation in Vue project
- Analyse du principe de mise en œuvre d'un éditeur de texte open source markdown - to - rich
猜你喜欢

Li Kou brush question 338 Bit count

力扣刷题338.比特位计数

Day45. data analysis practice (1): supermarket operation data analysis

Filter and listener
![[kubernetes series] pod chapter actual operation](/img/ac/fb563f3d92e6fdbd36e41d2f213556.jpg)
[kubernetes series] pod chapter actual operation

Introduction and use of ES6

Reread the classic: end to end object detection with transformers

Uni app dynamic add style dynamic bind background image invalid
![[flutter problem Series Chapter 67] the Solution to the problem of Routing cannot be jumped again in in dialog popup Using get plug - in in flutter](/img/59/0d95619ee3bba1f8992d90267d45c2.png)
[flutter problem Series Chapter 67] the Solution to the problem of Routing cannot be jumped again in in dialog popup Using get plug - in in flutter

Simple static web page + animation (small case)
随机推荐
EMC整改纲要
R: Employee turnover forecast practice
Et framework -22 creating serverinfo entities and events
120. 三角形最小路径和-动态规划
剑指 Offer 56 - I. 数组中数字出现的次数
SQL 进阶挑战(1 - 5)
How to use debounce in lodash to realize anti shake
Billions of data to determine whether the element exists
Reread the classic: end to end object detection with transformers
The problem that ionic3 cannot automatically install the APK package
This Sedata uses multiple methods to dynamically modify objects and values in arrays. Object calculation properties
Zoom and move the H5 part of the mobile end
dumi 搭建文档型博客
El expression
Interpretation and implementation of proxy mode
环评图件制作-数据处理+图件制作
剑指 Offer 11. 旋转数组的最小数字-二分查找
Advanced Mathematics (Seventh Edition) Tongji University exercises 1-2 personal solutions
Koa file upload and download
Modeling discussion series 143 data processing, analysis and decision system development