SoFunction
Updated on 2025-04-08

Steps to create a web server using express based on nodejs

1. Create a web server

1. Initialize the project and install the express package

Initialize the project

npm init -y

Install express

npm i express

2. Create a server

1. Create a file 2. Import express 3. Create a server 4. Call listen to start the server (listen passes in two parameters: port number, callback function) 5. Use node to start the program in the current directory, and the console prints out: Server is running on port 3000, which means that the server is successfully started on port 3000.

// Import expressconst express = require('express')
// Create a serverconst app = express()
// Call listen to start the server(3000, () => {
    ('Server is running on port 3000')
})
node 

3. Listen to get and post request

Listen to get, post request (req: request parameters, res: response parameters), and use (data) to respond to data to the web segment

// Listen to GET requests('/', (req, res) => {
    ('Hello, GET request received!')
})
// Listen to POST requests('/', (req, res) => {
    ('Hello, POST request received!')
})

4. Get request parameters

The web terminal passes parameters to the server, and can pass parameters through params, query, and body. Generally, get requests use params, query to pass parameters, and post requests use body to pass parameters. 1. get requests use params to get parameters, request url:http://127.0.0.1:3000/test/123, the web gets the response id: 123

// Get params parameters('/test/:id', (req, res) => {
    const id = 
    (`id: ${id}`)
})

3. Post request uses body to get parameters, request url:http://127.0.0.1:3000/test. For post requests, we first use middleware to parse the requested form data. The form data in x-www-form-urlencoded format is parsed through middleware, where extended: false means that third-party libraries are not used to process nested objects. If you need to process other types of data (such as JSON data), you can use middleware. (The middleware concept will be introduced in detail later) Request data: {id: 123, name: whg}, response data: testData: {id: 123, name: whg}

(({ extended: false }))
(())
// Get body parameters('/test', (req, res) => {
    const testData = 
    (`testData: ${testData}`)
})

2. Express routing

In Express, Routing refers to the process of mapping different HTTP requests to the corresponding handler or controller. Express provides a simple and flexible way to define and manage routing, enabling developers to handle different URL paths and HTTP methods.

1. Use the routing directly

Listen to get, /test route in post request, when the request url ishttp://127.0.0.1:3000/testWhen entering the corresponding request processing function

// Listen to GET requests/test routes('/test', (req, res) => {
    ('Hello, GET request received!')
})
// Listen to POST requests/test routes('/test', (req, res) => {
    ('Hello, POST request received!')
})

2. Use the router

A router is a middleware that combines related routes with common path prefixes. It can be regarded as a standalone module that handles specific URL paths. Use a router to organize the application's routing logic into a modular way to improve the maintainability and readability of the code. Create a user login to register the router module:

// Import expressconst express = require('express')
// Create a routerconst router = ()
// Use the router to listen to the route('/login', (req, res) => {
    ('login success')
})
('/register', (req, res) => {
    ('register success')
})
// Export the router = router

Create user information-related router module:

// Import expressconst express = require('express')
// Create a routerconst router = ()
// Use the router to listen to the route('/setUserInfo', (req, res) => {
    ('setUserInfo success')
})
('/getUserInfo', (req, res) => {
    ('getUserInfo success')
})
// Export the router = router

Import and register the router. When registering a route, two parameters can be passed in. The first parameter is a unified prefix (optional, if you do not pass, there will be no prefix by default), and the second parameter is the router. When the url ishttp://127.0.0.1:3000/loginWhen entering the login routing processing function, when the url ishttp://127.0.0.1:3000/api/setUserInfoWhen entering the setting user information routing processing function

// Import the routerconst userRouter = require('./users')
const userInfoRouter = require('./userInfo')
// Register a route(userRouter)
('/api', userInfoRouter)

3. Encapsulate routing processing functions

Further modularize the routing-related logic (taken as an example) Create a routerHandler folder and store files (note that the file name is the same as the router folder, which can clearly see the one-to-one correspondence between the router file and the processing function file)

// Login routing processing function = (req, res) => {
    ('login success')
}
// Register the routing processing function = (req, res) => {
    ('register success')
}

Create a router folder and store files

// Import expressconst express = require('express')
// Create a routerconst router = ()
// Import routing processing functionsconst { login, register } = require('../routerHandler/')
// Use the router to listen to the route('/login', login)
('/register', register)
// Export the router = router

3. Express middleware

Express middleware (Middleware) is a functional component that handles HTTP requests between requests and responses. Middleware functions can access the request object (req), the response object (res), and the next middleware function (next) of the application. Middleware functions can be used to perform various tasks, such as authentication, logging, error handling, etc. Using middleware can break down the application's processing logic into reusable and composable parts, improving the maintainability and scalability of the code. Middleware is roughly divided into the following 5 types. Let’s use the modular idea to place all custom middleware in the file in the common folder.

1. Application-level Middleware

Application-level middleware is also known as global middleware, which are bound to application objects (apps) and executed before all routes. They can be used to handle application-level tasks such as logging, authentication, error handling, etc. Use the() method to add application-level middleware to the application. The next() method must be called in the middleware function, otherwise an error will be reported.

// Define an application-level middleware that encapsulates the() method = (req, res, next) => {
     = (status, message, data) => {
        ({
            status,
            message,
            data: data ? data : null
        })
    }
    next()
}

Note: Global middleware should generally be placed before routing middleware

// Import middlewareconst { resSendMiddleware } = require('../common/')
// Register global middleware(resSendMiddleware)
// Register routing middleware// TODO

2. Router-level Middleware

Routing-level middleware, also known as local middleware, These middleware are bound to a specific route and executed before a specific route handler. They are used to perform some operations on a specific route, such as authentication, request processing, etc. Use() to create a routing object, and then use() to add the routing middleware to the routing object.

// Define a routing-level middleware that encapsulates verification of login data legitimacy = (req, res, next) => {
    const userInfo = 
    // Verification logic    // TODO
    next()
}
// Import routing processing functionsconst { login, register } = require('../routerHandler/')
// Import middlewareconst { verifyLogin } = require('../common/')
// Use the router to listen to the route('/login', verifyLogin, login)
('/register', register)
// Export the router = router

3. Error Handling Middleware

These middlewares are used to handle errors that occur in the routing handler. They are defined after other middleware and routing handlers and use four parameters (err, req, res, next) to catch the errors and process them. Use() to add error handling middleware to your application.

// Define an error middleware to catch errors = (err, req, res, next) => {
    if ( === 'UnauthorizedError') {
        // JWT authentication failed        (401, 'Identity authentication failed')
    }
}
// Import middlewareconst { resSendMiddleware, handleError } = require('../common/')
// Register global middleware(resSendMiddleware)
// Register a route// TODO
// Registration error middleware(handleError)

4. Third-party Middleware

These middleware are created by third-party developers and can be installed through NPM and used in Express applications. Third-party middleware can provide various functions, such as authentication, logging, compression, etc. Use() to add third-party middleware to the application. For example, after handling cross-domain middleware cors, you can directly reference and register after installing using npm i cors

// Import corsconst cors = require('cors')
// Import middlewareconst { resSendMiddleware, handleError } = require('../common/')
// Register the middleware to solve cross-domain problems(cors)
// Register global middleware(resSendMiddleware)
// Register routing middleware// TODO
// Registration error middleware(handleError)

5. Built-in Middleware

Express provides some built-in middleware that can be used directly in the application without installing additional packages. For example, (), () is used to parse requested JSON data, and () is used to provide static files, etc.

// Import corsconst cors = require('cors')
// Import middlewareconst { resSendMiddleware, handleError } = require('../common/')
// Register the middleware to solve cross-domain problems(cors)
// Register built-in middleware(({ extended: false }))
(())
(('public'))
// Register global middleware(resSendMiddleware)
// Register routing middleware// TODO
// Registration error middleware(handleError)

4. Hot code update

In order to avoid the need to execute node once after each code modification to rerun the code, we can install nodemon globally to monitor code modifications and automatically restart the application

npm install -g nodemon

Run the code

nodemon

The above is the detailed operation steps for creating a web server using express based on nodejs. For more information about creating a web server by nodejs express, please pay attention to my other related articles!