1. Getting started

const express = require('express'); //exprss returns a function const app = express(); App.get ('/',(req, res)=>{res.send('hello express'); })app.get('/list', (req, res)=>{ res.send({name:'wuxf', age:27})})app.listen(3000); // Start the listener port console.log(' start the service ');Copy the code

Code test:

Execute Node 01.js directly in expressStudy, and then test by typing http://localhost:3000/ in browseCopy the code

2. Middleware

What is middleware? Multiple middleware can be set up for the same request to process the same request multiple times. By default, requests are matched from top to bottom with the middleware. Once a match is made, the next method can be called to terminate the match and give control of the request to the next middleware until the middleware that ends the request is encountered

const express = require('express'); const app = express(); app.get('/request', (req, res, next)=>{ req.name = 'wuxf'; // Call the next middleware next() with the next method; })app.get('/request', (req, res)=>{ res.send(req.name); })app.listen(3000); Console. log(' start service ');Copy the code

3, Use

App.use matches all request modes and can be passed directly to the request handler to receive all requests. The first parameter can also pass in the request address, which means that whatever request is received at the request address, right

const express = require('express'); const app = express(); // Middleware app.use((req, res, next)=>{console.log(' app.use method '); next(); })// Middleware app.use('/request', (req, res, next)=>{console.log(' app.use /request request path '); next(); })app.use('/list', (req, res, next)=>{ res.send('/list'); })app.get('/request', (req, res, next)=>{ req.name = 'wuxf'; // Call the next middleware next() with the next method; })app.get('/request', (req, res)=>{ res.send(req.name); })app.listen(3000); Console. log(' start service ');Copy the code

4. Middleware application

1. Route protection: When accessing the page to be logged in, the client can use the middleware to determine the user’s login status. If the user does not log in, the client intercepts the request and responds directly to prevent the user from accessing the page to be logged in. Website maintenance bulletin, at the top of all routes define middleware to receive all requests, respond directly to the client, the website is being maintained 3. Customize 404 pages

const express = require('express'); const app = express(); // app.use((req, res, next)=>{// res.send(' this website is being maintained... ') / /}) / / receive all requests of middleware app. Use ('/admin '(the req, res, next) = > {let login = true; if( login ){ next(); }else{res.send(' You haven't logged in yet, please log in first '); }}) app. Get ('/admin '(the req, res) = > {res. Send (' login success); })// Customize 404 pages and HTTP status code app.use((req, res, next)=>{res.status(403).send(' currently accessed page does not exist '); })app.listen(3000); Console. log(' start service ');Copy the code

5. Error handling middleware

1. During program execution, errors will inevitably occur, which will be handled centrally by the error middleware. To handle asynchrony, use the next() method and pass the error message to the next() method to start the error middleware

const express = require('express'); const fs = require('fs'); const app = express(); App. use('/err/sync', (req, res, next)=>{throw new Error(' test Error '); })// When an error occurs in an asynchronous task, With the next () method is passed the error app. Use ('/err/async '(the req, res, next) = > {fs. ReadFile ('. / err. Js',' utf-8, (err, result) = > {if (err! = null) {next (err)} else {res. Send (result)}})}) app. Get ('/list ', (the req, res) = > {res. Send (' successful request); })// Middleware app.use((err, req, res, next)=>{res.status(500).send(err.message); })app.listen(3000); Console. log(' start service ');Copy the code

6, try catch error

//1. A try catch can catch synchronous or asynchronous functions, but not callback functions. const express = require('express'); const fs = require('fs'); const promisify = require('util').promisify; const readFile = promisify(fs.readFile); const app = express(); App. use('/err', async (req, res, next)=>{try {await readFile('err.js'); } catch(ex) { next(ex); }}) app. Get ('/list ', (the req, res) = > {res. Send (' successful request); })// Middleware app.use((err, req, res, next)=>{res.status(500).send(err.message); })app.listen(3000); Console. log(' start service ');Copy the code

7. Route encapsulation

When the page request path is large, the route is encapsulated

const express = require('express'); const app = express(); // Create a route object const user = express.router (); // Match the request path for the routing object app.use('/user', user); / / create a secondary routing, request path to/user/adduser. Get ('/add ', (the req, res) = > {res. Send (' add user '); }) user. Get ('/delete '(the req, res) = > {res. Send (' delete users'); })app.listen(3000); Console. log(' start service ');Copy the code

8. Modular routing

const express = require('express'); const app = express(); const user = require('./route/user.js'); const product = require('./route/product.js'); // Match the request path for the routing object app.use('/user', user); app.use('/product', product); app.listen(3000); Console. log(' start service '); // const express = require('express'); const user = express.Router(); The user. The get ('/query '(the req, res) = > {res. Send (' return to the customer data); })module.exports = user;Copy the code

9. Get the GET request parameters

const express = require('express'); const app = express(); App. Use ('/index, (the req, res) = > {/ / the req. Query for the get request parameters / / http://localhost:3000/index? Aaa = 111 & BBB = 222 & CCCC = 444 / / results for: {" aaa ":" 111 ", "BBB" : "222", "CCCC" : "444"} res. Send (the req. Query); })app.listen(3000); Console. log(' start service ');Copy the code

10. Get the POST request parameters

const express = require('express'); const bodyParser = require('body-parser'); const app = express(); // Intercept all requests // extended: The false method internally uses the queryString module to handle request parameters // extended: App. use(bodyParser.urlencoded({extended: coded); False})) / / post page request app. Use ('/index, (the req, res) = > {res. Send (the req. Body); })app.listen(3000); Console. log(' start service ');Copy the code

11. The function passed in app.use is executed as middleware

const express = require('express'); const bodyParser = require('body-parser'); const app = express(); function fn(params){ return function(req, res, next){ console.log(params); Console. log(' custom middleware functions '); next(); }// Any request will be intercepted app.use(fn({par:'foo'})); App. Use ('/index, (the req, res) = > {res. Send (' testing custom middleware functions'); })app.listen(3000); Console. log(' start service ');Copy the code

12. Dynamic routing parameters

const express = require('express'); const app = express(); // Req.params obtains dynamic route parameters. // Route parameters depend on the URL. If the path is matched as follows, level 3 route parameters need to be passed. But the user, the age is a dynamic acquisition / / http://localhost:3000/index/wuxf/27app.use ('/index / : user / : age, (the req, res) = > {res. Send (the req. Params); })app.listen(3000); Console. log(' start service ');Copy the code

Static resource access

const express = require('express'); const path = require('path'); const app = express(); / / can be tested through the link: http://localhost:3000/static/button.htmlapp.use ('/static, express the static (path. Join (__dirname, 'static')))app.listen(3000);Copy the code

// The static resource directory is static

Template engine

// Create a template engine by using art-template as an example. NPM install art-template express-art-templateconst express = require('express'); const path = require('path'); const app = express(); App. engine('art', require('express-art-template')); app.engine('art', require('express-art ')); App. set('views', path.join(__dirname, 'engine')); // Set the express framework template to app.set('view engine', 'art'); App. use('/engineTest', (req, res)=>{// Render template 1: which template file to use // Res.render ('first', {first:'hello first'}); })app.listen(3000); Console. log(' start service ');Copy the code

The template engine contents are:

<div>{{first}}</div><div>{{common}}</div>
Copy the code

15. Template engine Different templates share variables

// Create a template engine by using art-template as an example. NPM install art-template express-art-templateconst express = require('express'); const path = require('path'); const app = express(); App. engine('art', require('express-art-template')); app.engine('art', require('express-art ')); App. set('views', path.join(__dirname, 'engine')); // Set the express framework template to app.set('view engine', 'art'); Mon = {name:'wuxf'}// Map the template to the requested path. App. use('/engineTest', (req, Res.render ('first', {first:'hello first'}); // Render ('first', {first:'hello first'}); })app.use('/engineTwo', (req, res)=>{ Res.render ('two', {two:'hello two'}); })app.listen(3000); Console. log(' start service ');Copy the code