An overview of the
Express_ is a flexible Node.js Web application _ framework that maintains minimal scale and provides a powerful set of capabilities for Web and mobile applications. Is a further encapsulation of the native HTTP module
use
The installation
npm install express
Request and Response objects
The first is the Request object, which is usually represented by the REQ variable. Here are some of the more important members of reQ:
-
Req.body: Data for the client request body, which could be form or JSON data
-
Req.params: Path parameter in the request URI
-
Req.query: query parameter in the request URI
-
Req. cookies: indicates the cookies of the client
Then there is the Response Response object, usually represented by the RES variable, which can perform a series of Response operations
// Send a String of HTML code res.send('HTML String'); // Send a file res.sendfile ('file.zip'); // Render a template engine and send res.render('index');Copy the code
Routing mechanism
When the client (Web front-end, mobile, and so on) makes a request to the server, it contains two elements: the path (URI) and the HTTP request method (GET, POST, and so on). Together, the path and request methods are commonly referred to as API endpoints. The mechanism by which the server selects the appropriate processing logic based on the endpoint accessed by the client is called routing.
Define the routing mode
app.METHOD(PATH, HANDLER)
app
Is aexpress
Server objectMETHOD
It could be anythinglowercaseHTTP request methods, includingget
,post
,put
,delete
, etc.PATH
Is the URI accessed by the client, for example/
或/about
HANDLER
Is the callback function when the route is triggered. The corresponding service logic can be executed in the function
A small example of implementation
const express = require("express");
const hostname = "localhost";
const port = 3000;
const app = express();
app.get("/", (req, res) => {
res.send("Hello World");
});
app.listen(port, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Copy the code
NPM run start (configured in package.json ahead of time)
You can see the program executing. Open http://localhost:3000 to check
You can see that the GET request was successful
The middleware
First the client initiates a request to the server, then the server executes each middleware in turn, finally reaching the route and choosing the appropriate logic to execute.
Two points in particular need to be noted:
-
Middleware executes sequentially, so that order is very important when configuring middleware
-
The middleware can either pass the request to the next middleware while executing the internal logic or return the user response directly
Definition of Express middleware
In Express, middleware is a function:
Function someMiddleware(req, res, next) {// Next (); }Copy the code
Of the three parameters, req and RES are the previously mentioned Request object and Response object. The next function is used to trigger the next middleware execution.
Pay attention to
If you forget to call the next function in the middleware and do not return a response directly, the server will get stuck in the middleware and not continue execution.
There are two ways to use middleware in Express: global **** middleware and routing **** middleware.
Global middleware
The middleware can be registered with the app.use function
Routing middleware
By registering middleware at route definition time, this middleware is executed only when the user accesses the URI corresponding to the route, for example:
app.get('/middleware', someMiddleware, (req, res) => {
res.send('Hello World');
});
Copy the code
The someMiddleware middleware defined is triggered only when the user accesses/Middleware, not when the user accesses other paths.
Writing middleware
Let’s start implementing our first Express middleware. It simply prints the client’s access time, HTTP request methods, and URIs on a terminal called loggingMiddleware. The code is as follows:
// ...
const app = express();
function loggingMiddleware(req, res, next) {
const time = new Date();
console.log(`[${time.toLocaleString()}] ${req.method} ${req.url}`);
next();
}
app.use(loggingMiddleware);
app.get('/', (req, res) => {
res.send('Hello World');
});
// ...
Copy the code
The middleware can not only read individual attributes on the REQ object, but also add new attributes or modify existing attributes (later middleware and routing functions can obtain), which can easily implement some complex business logic (such as user authentication).
Handle 404 and server errors
There are two important differences between this diagram and the previous one:
-
Each route definition is essentially a middleware (more specifically, a middleware **** container, which can contain multiple middleware) that returns a response when a URI match is successful and continues to execute the next route when the match fails
-
Each middleware (including routing) can not only call the next function to pass down and return the response directly, but can also throw an exception
-
For 404, just add a middleware after all the routes to receive the request that all the routes failed to match
-
For error handling, all previous middleware exceptions go into error handling functions, which can be used with Express or customized.
Handle 404
In Express, access to non-existent paths can be handled through middleware:
App. Use (' * '(the req, res) = > {/ / * means to match any path, put all routing behind the middleware}); // Middleware and other routing... app.use('*', (req, res) => { res.status(404).render('404', { url: req.originalUrl }); }); app.use((err, req, res, next) => { console.error(err.stack); res.status(500).render('500'); }); app.listen(port, () => { console.log(`Server running at http://${hostname}:${port}/`); });Copy the code
Use child routing
In Express, we can implement this through the subroute Router
*
Express. Router can be thought of as a mini app object, but it is fully functional and also supports registering middleware and routing:
// Register a middleware router. Use (someMiddleware); Router.get ('/hello', helloHandler); router.post('/world', worldHandler);Copy the code
Finally, you only need to add the Router as middleware to the app
*
Add all routes to the router under /say.
app.get('/say/hello', helloHandler);
app.post('/say/world', worldHandler);
Copy the code
experience
This is just a taste of a basic use of Express, which is extensive and will be supplemented by further documentation