当前位置:网站首页>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
边栏推荐
- Wechat applet - wechat applet browsing PDF files
- Argocd Web UI loading is slow? A trick to teach you to solve
- Shell programming specifications and variables
- Redis 基本知识,快来回顾一下
- 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}
- MySQL how to add users and set permissions?
- PHP Basics - PHP uses PDO
- [opencv] generate transparent PNG image
- Gbase 8A MPP and Galaxy Kirin (x86 version) complete deep adaptation
- Blog Building 9: add search function to Hugo
猜你喜欢

What are the main uses of digital factory management system

分布式系统架构理论与组件
![第2章-2 计算分段函数[1]](/img/40/cad6bf92849624199af0fd1ba1d433.jpg)
第2章-2 计算分段函数[1]

XMIND Zen installation tutorial

NDK 系列(6):说一下注册 JNI 函数的方式和时机

Two dimensional array and operation

Leetcode brushes questions. I recommend this video of the sister Xueba at station B

Baidu AI Cloud Jiuzhou district and county brain, depicting a new blueprint for urban and rural areas!

When unity switches to another scene, he finds that the scene is dimmed

The cooperation between starfish OS and metabell is just the beginning
随机推荐
[soft test software evaluator] 2013 comprehensive knowledge over the years
Vk1620 temperature controller / smart meter LED digital display driver chip 3/4-wire interface with built-in RC oscillator to provide technical support
Analysis and recurrence of network security vulnerabilities
Top all major platforms, 22 versions of interview core knowledge analysis notes, strong on the list
Win the bid! Nantah general gbase 8s won the bid for the 2022 database framework project of NARI Group
第2章-2 计算分段函数[1]
Network interface network crystal head RJ45, Poe interface definition line sequence
解决:IndexError: index 13 is out of bounds for dimension 0 with size 13
I am a 27 year old technical manager, whose income is too high, and my heart is in a panic
创建线程的3种方式
After reading these 12 interview questions, the new media operation post is yours
PHP基础知识 - PHP 使用 MySQLI
Eight ways to solve EMC and EMI conducted interference
博客搭建九:hugo添加搜索功能
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}
说透缓存一致性与内存屏障
I use SqlClient normally, and dlink submission will report this error. What should I do?
Recycling of classes loaded by classloader
置顶各大平台,22版面试核心知识解析笔记,强势上榜
[opencv] generate transparent PNG image