Express basic operations and detailed explanations

Express basic operations and detailed explanations

Express.js is a web application framework based on the Node.js platform, which is designed to help developers easily build and manage web services and applications. Express provides many powerful features that make it relatively easy to create scalable, flexible, and high-performance Web applications. Here are the main features of Express and a detailed explanation of some core concepts:

Insert image description here

Install Express.js

Before starting, make sure you have Node.js and npm installed. Next, you can use npm to install Express.js:

npm install express

Create a simple Express application

First, create a app.jsfile named for writing the Express application. Then, follow these steps to create a simple Express app:

Step 1: Import Express module

In app.jsthe file, first import the Express module:

const express = require('express');
const app = express();

Step 2: Create a GET request handler

Using Express, you can create different types of routes to handle different HTTP requests. Here is a simple GET request handler for /GET requests on the root path:

app.get('/', (req, res) => {
    
    
  res.send('Hello, Express!');
});

In the above code, we app.get()create a GET request handler using the method. When the user accesses the root path /, the server will respond with "Hello, Express!".

Step 3: Launch the Express application

Finally, at the end of the file, add the following code to start the Express app and listen on the port:

const port = 3000;

app.listen(port, () => {
    
    
  console.log(`Express app listening at http://localhost:${
      
      port}`);
});

This will start the Express application and listen on the port 3000. You can change the port number as needed.

Run the Express application

In the terminal, run the Express app with the following command:

node app.js

1. Routing processing

Express provides a simple and flexible routing system for handling requests with different HTTP request methods (such as GET, POST, PUT, DELETE) and URL paths. Through routing, you can map requests to specific handler functions to implement responses to different URL paths.

Example:

app.get('/', (req, res) => {
    
    
  res.send('Hello, Express!');
});

app.post('/user', (req, res) => {
    
    
  // 处理 POST 请求
});

2. Middleware

Express middleware is a chain of functions that perform some action before or after the request reaches the route handler. Middleware can handle tasks such as authentication, logging, request parsing, etc. Middleware can be added, arranged, and customized as needed.

Example:

// 自定义中间件
app.use((req, res, next) => {
    
    
  console.log('Request received at: ', new Date());
  next(); // 调用下一个中间件或路由处理程序
});

3. Template engine

Express allows you to use various template engines (such as EJS, Pug, Handlebars) to render dynamic HTML pages. This makes it easy to build server-side rendered applications.

Example:

app.set('view engine', 'ejs');
app.get('/profile', (req, res) => {
    
    
  res.render('profile', {
    
     name: 'John' });
});

4. Static file service

Through express.staticmiddleware, Express can easily serve static files (such as CSS, JavaScript, images) without writing additional routes for them.

Example:

app.use(express.static('public'));

Core idea:

1.Object app_

appObjects are the core of Express applications and contain routing, middleware, and other configuration. You can use appobjects to define routes, set up middleware, start servers, etc.

const express = require('express');
const app = express();

2. Routing

Routes are mapping rules that define request handlers. Express uses different HTTP request methods (such as GET, POST) and URL paths to match routing rules and execute appropriate handlers.

3. Middleware

Middleware is a chain of functions that handle requests and responses. It can perform various tasks such as authentication, logging, request parsing, etc. before or after the request reaches the handler.

4. Request ( req) and response ( res)

reqThe object represents the client request and contains information about the request (such as URL, HTTP headers, request body, etc.). resObject is used to construct and send responses to the client.

5. Listening port

Use app.listen()the method to start an Express application and listen on the specified port number to accept incoming requests.

Example:

const port = 3000;
app.listen(port, () => {
    
    
  console.log(`Server is running on port ${
      
      port}`);
});

6. Error handling

Express provides a mechanism to handle errors, and you can use middleware to catch and handle errors in your application.

Example:

app.use((err, req, res, next) => {
    
    
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

You will see output in the terminal indicating that the Express application is running on the specified port. Now, you can access it in a browser or API tool http://localhost:3000/, and you should see a "Hello, Express!" response.
Insert image description here
The above is the basic operation and detailed explanation of Express. Thank you for reading.
If you encounter other problems, you can discuss and learn with me privately.
If it is helpful to you, please 点赞bookmark it. Thank you~!
Follow the favorite blog author for continuous updates...

Guess you like

Origin blog.csdn.net/qq2754289818/article/details/133274338