Learn from scratch node. js express Getting Started of VI
- 2021-07-24 09:41:57
- OfStack
1. Introduction
What is express and why use express? According to the official website, express is a minimalist and flexible web application development framework based on Node. js platform. It provides a series of powerful features, rich API interfaces, encapsulates web application interfaces twice, and provides MVC mode, which is convenient for us to quickly create various web and mobile applications.
Express Framework Core Features:
This article is just a simple understanding of the content of express framework. I hope everyone can get started quickly. For more detailed content, read official website and check the related API.
Official Chinese website of express: "Express"
STEP 2 Getting Started
Create a directory myapp. After entering myapp, use the command
npm express --save-dev
Install express locally and create app. js (or server. js) as the entry to the program.
// app.js
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000, function(){
console.log('server has running at port 3000');
})
Run the app. js file:
$ node app.js
server has running at port 3000
Visit http://127.0. 0.1: 3000/in the browser to see hello world output on the page. Explain that the basic express program can run normally.
2.1 APP
After the express module is introduced, execute the
express()
An example of app is obtained, and get, post, use and listen are included in the example of app.
app.get(path, handler)
When using the get method to access the path path, the method specified by handler is executed, and the handler method also takes two parameters req and res for our use. req is the information when the request comes, such as parameters query, body, header header, etc. res is the information setting that we want to return to the browser as a server.
res.send(‘hello world')
Indicates that the 'hello world' string is sent to the page.
Of course, if you want to receive requests from post, you can use
app.post(path, function(req, res){})
A request from post to path is received.
app.listen
Used to listen to the local port after running the web program, listening successfully after the execution of the callback function.
2.2 Routing
We explained "Learning node from scratch. Building http Server from js (2)" before, and also said the content of 1-point routing, but the routing rules we formulated at that time were very simple, and only handled about 3 pages. While express enriches routing functions.
At the same time, we should also pay attention to the fact that/means under the root path and/user means under the user path. If you access the/user/login, you will directly access the/user/login route, but the first two routes will not be accessed.
// Requests under the root path
app.get('/', function(req, res){
console.log('hello world');
res.send('hello world');
});
// /user Request under the path
app.get('/user', function(req, res){
console.log('user');
res.send('huser');
});
// /user/login Request under
app.get('/user/login', function(req, res){
console.log('user/login');
res.send('user/login');
});
Moreover, path paths can be routed by string matching and regular matching.
2.3 RES Response Method
In the example just above, we use
res.send()
Outputs a plain text string of 'hello world' to the page, and
res.send()
You can also output other types of data, such as html strings (which can be parsed by browsers), Buffer types, Object types, Array types, and so on.
For example, we want to output 1 html string.
var html = '<!DOCTYPE html>\
<html lang="en">\
<head>\
<meta charset="UTF-8" />\
<title>Document</title>\
</head>\
<body>\
<div>\
<p style="color:#f00;">hello world</p>\
<p><input type="text" /></p>\
</div>\
</body>\
</html>';
app.get('/', function(req, res, next){
res.send(html);
});
We can have a red hello world and a text input box on the browser. But if the code for html is long, we can put it all in a separate html file and use the
res.sendFile()
Method to output the contents of the html file to the page.
Create an index. html file in the root directory, put the complete html code in, and then:
app.get('/', function(req, res, next){
res.sendFile('index.html');
});
In this way, you can see a complete page in the browser.
In addition, res also provides one other method for us to use:
方法 | 描述 | |
---|---|---|
res.download() | 下载文件。 | |
res.end() | 终结响应处理流程。 | |
res.json() | 发送1个 JSON 格式的响应。 | |
res.jsonp() | 发送1个支持 JSONP 的 JSON 格式的响应。 | |
res.redirect() | 重定向请求。 | |
res.render() | 渲染视图模板。 | |
res.send() | 发送各种类型的响应。 | |
res.sendFile | 以8位字节流的形式发送文件。 | |
res.sendStatus() | 设置响应状态代码,并将其以字符串形式作为响应体的1部分发送。 |
3. Middleware
We execute above
app.get('/', function(){})
The callback function inside is middleware. Middleware is actually a function, which is used
express()
0
,
app.post
,
app.use
And so on, you are calling middleware as a callback function. Middleware can call req and res objects. If multiple middleware execute downward in sequence, one next variable is needed in the middle of the previous middleware to call the next middleware.
Here
app.use
The use method of is the same as that of
express()
0
1, both have two parameters: path and callback function, and here, the path parameter can be ignored (ignoring it will execute the middleware for each request).
// The middleware responds to any request
app.use(function(req, res, next){
console.log('index m url: '+req.url);
next(); // If not next() The request is suspended, 1 Wait straight
})
// /topic Will respond to the request under, including /topic/1.html, /topic/c/1.html Etc
app.use('/topic', function(req, res, next){
console.log('topic m url: '+req.url);
next();
})
// Deal with / Requests under the root directory
app.get('/', function(req, res, next){
res.send('index');
});
// Deal with /topic/1.html This type of request
app.get('/topic/:id.html', function(req, res, next){
res.send('topic');
});
Let's type 1 different url in the browser to see:
url | 控制台输出 | 浏览器输出 | 说明 |
---|---|---|---|
127.0.0.1:3000 | index m url: / | index | |
/user | index m url: /user | Cannot GET /user | 中间件响应了不存在页面的请求 |
/topic/1.html | index m url: /topic/1.html topic m url: /1.html |
topic | 两个use中间件都响应了请求 |
/topic/c/1.html | index m url: /topic/c/1.html topic m url: /c/1.html |
Cannot GET /topic/c/1.html | 两个use中间件都响应了请求,只是没有路由来对该url进行处理 |
At the same time,
app.use()
And
app.get()
And so on, you can call multiple middleware to execute in turn, using
next()
Give control to the next middleware. Multiple middleware can be passed in one by one as a transport, all in an array, or a mixture of the two (
express()
0
In the same way):
app.use(path, m1, m2, m3, m4...);
app.use(path, [m1, m2, m3, ...]);
app.use(path, [m1, m2, m3, ...], m7, m8, ...);
Based on the above code, we write multiple middleware.
// As an array
app.use([
function(req, res, next){
console.log('index m 1');
next();
}, function(req, res, next){
console.log('index m 2');
next();
}, function(req, res, next){
console.log('index m 3');
next();
}
])
// Each middleware acts as a 1 Parameters
app.get('/topic/:id.html', function(req, res, next){
// res.send('topic');
console.log('topic get 1');
next();
}, function(req, res, next){
console.log('topic get 2');
next();
}, function(req, res, next){
console.log('topic get 3');
res.send('topic');
});
When we access 127.0. 0.1/topic/1. html, we output:
index m 1
index m 2
index m 3
topic get 1
topic get 2
topic get 3
Explain that middleware executes downward in turn. We can do different processing in each middleware, but remember to use
next()
Method, or the page will hang up.
As we saw above in res, at least one method needs to be called, otherwise the request will be suspended, 1 wait, or 404. If there is no reply to the outside world, you can also use
app.get(path, handler)
0
End. At the same time, if a method in res is used in a middleware, the following middleware is no longer called.
Summarize
Here we also have a brief understanding of the express framework, and more content still needs to see the official website. After that, we will use express to build a simple forum system. Interested friends please continue to pay attention to this site.