Connect module of Node learning and the use of its Middleware
I. Overview
Connect
It is a tool set based on HTTP server, which provides a new way to organize code to interact with request and response objects, called middleware.
middleware
In fact, it is a simple JavaScript function, which not only handles req and res requests, but also receives a next function for flow control.
Benefits of using middleware:
1. The ability to make code more expressive (the ability to split applications into smaller units). 2. It can achieve good reuse.
- Example: / Connect /website
/* Path: / Connect/website/server.js */
//Modular dependency
var http = require('http');
var fs = require('fs');
//Create an http server
var server = http.createServer(function(req, res){
//Checking the request method is GET and the URL starts with / images and ends with.jpg
if('GET' == req.method && './images' == req.url.substr(0,7) && '.jpg' == req.url.substr(-4)){
//Check whether the file exists, _dirname gets the path of the current server
fs.stat(__dirname + req.url, function(err, stat){
if(err || !stat.isFile()){
res.writeHead(404);
res.end('Not Found !');
return;
}
serve(__dirname + req.url, 'application/jpg');
});
}
//If the URL is'/', then respond to index.html
else if('GET' == req.method && '/' == req.url){
serve(__dirname + '/index.html','text/html');
}else{
res.writeHead(404);
res.end('Not Found !');
}
//Obtain file content according to file path
function serve(path, type){
res.writeHead(200, {'Content-type':type});
fs.createReadStream(path).pipe(res);
}
});
//Listening port
server.listen(3000);
/* Path: / Connect/website/index.html */
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>website</title>
<style>
h1{
text-align: center;
}
img{
width: 300px;
height: 300px;
margin-left:20px;
}
</style>
</head>
<body>
<h1>Welcom to My Website</h1>
<img src="./images/1.jpg" alt="">
<img src="./images/2.jpg" alt="">
<img src="./images/3.jpg" alt="">
<img src="./images/4.jpg" alt="">
</body>
</html>
- Operation results
Introduction and Use of Middleware
1. static Middleware
Connect allows middleware to be mounted on a URL, and static allows any URL to be matched to any directory in the file system.
parameter
{maxAge:number}: Represents the time when resources are cached on the client side. {hidden:true/false}: Does the managed file that begins with (.) hide in the UNIX file system
Examples:
//Let my-imgURL correspond to a directory named / images
server.use('/my-img', connect.static('/path/to/images'));
//Merge all client JavaScript files into one file, add a revision number to the file name, and then set it to be cached forever.
server.use('/js', connect.static('/path/to/buddles), {maxAge;10000000000000});
server.use(connect.static('path/to/resources',{hidden:true});
2. query Middleware
Used to get the data part of the query string.
Sometimes the data sent to the server will be in the form of query string. Using query middleware, the data of query string can be automatically acquired through req.query object.
For example:
req.url == "/blog=posts?page=5"
that
req.query.page == "5"
3. logger Middleware
Used to print the incoming request information and the outgoing response information on the terminal.
Four log formats are provided:
default dev : Simple and short log format, which can provide information on behavior and performance, and facilitate testing Web Application. short tiny
Use examples: / Connect/example2
Running results: (browser side)
(Console)
4. body parser Middleware
Functions:
1. Data used to obtain POST requests.
Usage: server. use (connect. body Parser)
2. Processing files uploaded by users by using formidable module.
Single file upload: <input type="file"> Multi-file upload: <input type="file" name="files[]"> <input type="file" name="files[]">
Examples:
/* Path: / Connect/example3/example3.js */
//Modular dependency
var connect = require('connect');
//Create a server
var server = connect(
connect.bodyParser(),
connect.static('static'),
function(req, res, next ){
if('POST' == req.method && req.body.file){
//Add middleware to view the value of reqbody.file
//console.log(req.body.file);
fs.readFile(req.body.file.path, 'utf-8', function(err, data){
if(err){
res.writeHead(500);
res.end('Error!');
return;
}
res.writeHead(200, {'Content-Type':'text/html'});
res.end([
'<h3>File: ' + req.body.file.name + '</h3>',
'<h4>Type: ' + req.body.file.type + '</h4>',
'<h4>Content:</h4><pre>' + data + '</pre>'
].join(''));
});
}else{
next();
}
}
);
//Listening port
server.listen(3003);
/*Path: / Connect/example3/static/index.html */
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>example3</title>
</head>
<body>
<!--Processing uploaded files-->
<form action="/" method="POST" enctype="multipart/form-data">
<!--Single file upload-->
<input type="file">
<!--Multi-file upload-->
<input type="file" name="files[]">
<input type="file" name="files[]">
<button>Send file!</button>
</form>
</body>
</html>
Operation results:
4. cookieParser Middleware
Used to access values in Cookie header information.
Because session data is stored in memory, when the process exits, session data disappears in order to be able to see
If the information is persisted, Redis can be used.
Redis is a small and fast database with a connect-redis module that uses Redis to persist session data so that sessions reside outside the Node process.
Usage: server.use(connect.session({store:new RediaStore, secret:'my secret'});
Example: / Connect/example4
Operation results:
When login with incorrect username or password:
Log in with the correct username and password:
When the browser re-enters: localhost:3004, because the previous login did not exit, the display will be as follows:
The console records the results:
5. Method Override Middleware
Some early browsers did not support PUT,DELETE,PATCH requests. The common solution was to add a _method variable to GET or POST requests to simulate those requests.
In addition, using the method Override middleware, the background processing program can be identified.
6. Basic Auth Middleware
Users perform basic authentication on the client.
Basic Auth uses User and pass as parameters and provides a callback function to tell whether the validation succeeds or fails.
Examples:
//Add basic Auth
connect.basicAuth(function(user, pass, fn){
process.stdin.write('Allow user \033[96m' + user + '\033[39m' + 'with pass \033[90m' + pass + '\033[39m ? [y/n]: ');
process.stdin.once('data', function(){
if(data[0] == 'y'){
fn(null,{username:user});
}else{
fn(new Error('Unauthorized'));
}
});
});
Summary:
The advantage of using middleware is that the code can be organized as a building block and achieve high reusability.
Connect is a module to implement this idea, which provides a foundation for building more expressive middleware.