当前位置:网站首页>Detailed explanation of the basic use of express, body parse and express art template modules (use, route, path matching, response method, managed static files, official website)
Detailed explanation of the basic use of express, body parse and express art template modules (use, route, path matching, response method, managed static files, official website)
2022-07-28 08:56:00 【YF-SOD】
Catalog
express
be based on Node.js platform , Fast 、 to open up 、 minimalist web Development framework . following app=express().
app.use
visit http://localhost:8080/api/apple/yf, because 4 The callback function of does not execute next() Therefore, it will not match down . The code log output localhost:8080 0 1 2 3 4; Web output end.
const express = require("express");
const app = express();
const middlewares = [
(req, res, next) => {
console.log(0);
next();
},
(req, res, next) => {
console.log(1);
next();
},
];//middlewares Is an array , The array contains callback functions , When in the first callback function next() Execution time , The following functions will continue to execute .
app.use("/", middlewares);// The matching request path contains http://localhost:8080/.
//app.use Will match from top to bottom , When matching to the path , If there is no next() perform , Will not continue to match down ( It's over ).
app.use(
"/api",
(req, res, next) => {
console.log(2);
next();
},
(req, res, next) => {
console.log(3);
res.send("end");
next();
}
);
app.use("/api/apple", (req, res) => {
console.log(4);
});
app.use("/api/apple/yf", (req, res) => {
console.log(5);
});
app.listen(8080, () => {
console.log("localhost:8080");
});// visit http://localhost:8080/api/apple/yf, because 4 The callback function of does not execute next() Therefore, it will not match down . The code log output localhost:8080 0 1 2 3 4; Web output end.app.route
You can use app.route() Create a chained routing handle to the routing path . Because the path is specified in one place , This helps to create modular routes , And reduce code redundancy and spelling errors .
The following example program uses app.route() A chained route handle is defined .
app.route('/book')
.get(function(req, res) {
res.send('Get a random book');
})
.post(function(req, res) {
res.send('Add a book');
})
.put(function(req, res) {
res.send('Update the book');
});Path matching
Character matching
You can use ?、+、* and () Match , except * The other meaning of extra is the same as regular .
// ? Indicates one or zero occurrences , matching acd and abcd
app.get('/ab?cd', function(req, res) {
res.send('ab?cd');
});
// + Indicates one or more occurrences , matching abcd、abbcd、abbbcd etc.
app.get('/ab+cd', function(req, res) {
res.send('ab+cd');
});
// * For any character , matching abcd、abxcd、abRABDOMcd、ab123cd etc.
app.get('/ab*cd', function(req, res) {
res.send('ab*cd');
});
// () To represent a whole , matching /abe and /abcde
app.get('/ab(cd)?e', function(req, res) {
res.send('ab(cd)?e');
});
Regular matching
Regular expressions can be used directly for matching .
// Match any path containing a The path of :
app.get(/a/, function(req, res) {
res.send('/a/');
});
// matching butterfly、dragonfly, Mismatch butterflyman、dragonfly man etc.
app.get(/.*fly$/, function(req, res) {// Note that due to $ Symbol , The matching character must be at the end of the link except for the parameter .
res.send('/.*fly$/');
});express.Router()
visit http:localhost:8080/index?id=1 Webpage , Because it is get Request web page output index page, And then match /index in next() perform , So will app.use Will continue to match the output 0.
Be careful router.post\put\patch\delete\all Will only match one .
const express = require('express')
const router = express.Router()
//router.get Only match get request
router.get('/',(req,res,next)=>{
res.send('1')
})
router.get('/index',(req,res,next)=>{
console.log(req.query)// Output get Parameter object in the request {id:1}
res.send('index pages')
next()
})
//router.post matching post request
router.post('/index',(req,res,next)=>{
res.send(req.body)//post The parameters carried by the request are req.body in , But it needs to be used body-parser Module analysis , The output here is null , See the following module .
})
//router Will match accurately according to the request path , visit http://localhost:8080/index?id=1, Therefore, the web page will only output index page, And then match /index in next() perform , So will app.use Will continue to match the output 0.
router.put('/index',(req,res,next)=>{
res.send(req.body)
})// matching put Request for overwriting modification data
router.patch('/index',(req,res,next)=>{
res.send('patch')
})// matching patch Request for incremental modification of data
router.delete('/index',(req,res,next)=>{
res.send('delete')
})// matching delete request , Used to delete data
router.all('/index',(req,res,next)=>{
res.send('hello')
next()
})// matching post、get、put、patch、delete Wait for all request methods .
app.use('/',router)
app.use(()=>{
console.log(0)
})
app.listen(8080,()=>{
console.log('localhost:8080')
})Response method
The response objects in the following table (res) The method of returns a response to the client , End the cycle of request response . If a method is not called in the routing handle , Requests from clients will always hang .
| Method | describe |
|---|---|
| res.download() | Prompt to download files . |
| res.end() | End response processing flow . |
| res.json() | Send a JSON Response in format . |
| res.jsonp() | Send a support JSONP Of JSON Response in format . |
| res.redirect() | Redirecting Requests . |
| res.render() | Render view template . |
| res.send() | Send various types of responses . |
| res.sendFile | Send the file as an octet stream . |
| res.sendStatus() | Set response status code , And send it as a string as part of the response body . |
Hosting static files
adopt Express Built in express.static You can easily host static files , For example, pictures 、CSS、JavaScript Documents, etc. .
Pass the directory where the static resource file is located as a parameter to express.static Middleware can provide access to static resource files . for example , Suppose that public Pictures are placed in the directory 、CSS and JavaScript file , You can :
app.use(express.static('public'))
Now? ,public The files under the directory can be accessed .
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
The path of all files is relative to the storage directory , therefore , The directory name where the static file is stored will not appear in URL in .
If your static resources are stored in multiple directories , You can call express.static middleware :
app.use(express.static('public'))
app.use(express.static('files'))
When accessing a static resource file ,express.static The middleware will find the required files according to the order of adding directories .
If you want all to pass express.static The accessed files are stored in a “ fictitious (virtual)” Catalog ( That is, the directory does not exist ) below , This can be achieved by specifying a mount path for the static resource directory , As shown below :
app.use('/static', express.static('public'))
Now? , You can get through with “/static” Prefix address to access public The files under the directory .
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.htmlOfficial website
body-parser
For parsing express Module post Request parameters .
const express = require('express')
const router = express.Router()
const bodyParser = require('body-parser')
router.post('/index',(req,res,next)=>{
res.send(req.body)//post The parameters carried by the request are req.body in , Use body-parser Module analysis , The output here is post Parameters in the request .
})
//router Will match accurately according to the request path , visit http://localhost:8080/index?id=1, Therefore, the web page will only output index pages, But matching /index in next() perform , So will app.use Will continue to match the output 0.
// analysis post Request header Content-Type by application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended:false}))
// analysis post Request header Content-Type by application/json
// app.use(bodyParser.json())
app.use('/',router)
app.listen(8080,()=>{
console.log('localhost:8080')
})art-template
express-art-template
A simple and super fast template engine , Optimize template rendering speed through pre declared scope Technology , So as to realize the approach JavaScript Extreme runtime performance . meanwhile , It also supports NodeJS And browser .
const express = require("express");
const path = require("path");
const app = express();
app.engine("art", require("express-art-template")); // View engine settings
app.set("view options", {
debug: process.env.NODE_ENV !== "production",
escape: false,// Whether to translate symbols , The default is true
});
app.set("views", path.join(__dirname, "contentFile")); // Set the file that returns the content
app.set("view engine", "art");
app.get("/", function (req, res) {
res.header("Content-Type", "application/json;charset=utf-8"); // Note that according to the returned content , Set the return head , When to return to json Set when string . When not set , The default is text/html.
res.render("index.art", {
user: 'yf'
}); // Will be located at contentFile Under the index.art The contents of the file are returned , And in index.art The file can be referenced by double braces user Variable .
});{
name:{
{user}}
}visit http:localhost:8080/ The returned content is {'name':'yf'}.
Front end use
introduce
https://unpkg.com/[email protected]/lib/template-web.js
let templateStr = `
<ul>
{
{each data}}
<li>{
{$value}}</li>
{
{/each}}
</ul>
<div>{
{name}}</div>
`;
let html = template.render(templateStr, {
data: [{ value: 1 }, { value: 2 }],
name: "yf",
});
//html For the following string
// <ul>
// <li>1</li>
// <li>2</li>
// </ul>
// <div>yf</div>Using document
边栏推荐
- Redis 基本知识,快来回顾一下
- Analysis of model predictive control (MPC) (IX): numerical solution of quadratic programming (II)
- Analysis and recurrence of network security vulnerabilities
- Gbase appears in Unicom cloud Tour (Sichuan Station) to professionally empower cloud ecology
- 思迈特软件完成C轮融资,让BI真正实现“普惠化”
- Hcip day 8
- Deployment of kubernetes
- HCIP第九天_BGP实验
- JS inheritance method
- I am a 27 year old technical manager, whose income is too high, and my heart is in a panic
猜你喜欢

Use of tkmapper - super detailed

1w5字详细介绍分布式系统的那些技术方案

阿里技术四面+交叉面+HR面,成功拿到offer,双非本科进不了大厂?

Blog Building 9: add search function to Hugo

VS2015使用dumpbin 查看库的导出函数符号

Image batch processing | necessary skills

阿里巴巴内部面试资料

SQL Server查询结果导出到EXCEL表格

Distributed system architecture theory and components

SQL injection - pre Foundation
随机推荐
No one wants to tell the truth about kubernetes secret
Gbase appears in Unicom cloud Tour (Sichuan Station) to professionally empower cloud ecology
HCIP第八天
微服务架构 Sentinel 的服务限流及熔断
图片批处理|必备小技能
客户至上 | 国产BI领跑者,思迈特软件完成C轮融资
Flink window & time principle
我来教你如何组装一个注册中心?
Competition: diabetes genetic risk detection challenge (iFLYTEK)
Blog Building 9: add search function to Hugo
Source code analysis of linkedblockingqueue
Post it notes -- 45 {packaging of the uniapp component picker, for data transmission and processing -- Based on the from custom packaging that will be released later}
The five pictures tell you: why is there such a big gap between people in the workplace?
Blog building 7: Hugo
Redis 基本知识,快来回顾一下
思迈特软件完成C轮融资,让BI真正实现“普惠化”
Bash shell interaction free
Use of tkmapper - super detailed
Let me teach you how to assemble a registration center?
Digital signatures and Ca certificates