Develop a blog system using express and js (4)

Insert image description here

Static Resource Middleware

introduce

In web development, HTML, CSS, JS files and images are all called static resources. When we initiate a request in a web page, the data returned by the request interface is called a dynamic resource. Static resources generally do not need to be processed and are returned directly to the browser; while dynamic resources are generally processed by the backend, such as parsing the request URL and parameters sent by the front end and returning different JSON data according to different URLs and parameters.

It is easy to create a static resource server using the Express framework, just use the express.static() method.

Create a static resource server

Create a folder namedpublic in the root directory to store static resources such as CSS, JS, HTML, and images.

First, install the Express generator command line toolexpress-generator:

npm install express-generator -g

Then, use the Express generator to create a project skeleton:

express -e express-demo

Among them,-e parameter is used to specify the template engine used in the project.

After creation, enter the project directory and install the dependencies:

cd express-demo
npm install

Next, start the project:

DEBUG=express-demo:* npm start

Project structure introduction

The created project skeleton contains the following directories:

  • app.js: Express configuration file. We need to pay attention to this file. Most of the configuration has been generated. What needs to be added and modified is the routing configuration.
  • public/: Used to store static resource folders, including CSS, JS, HTML, images, etc.
  • routes/: Store routing module.
  • views/: Store HTML template files.
  • bin/: Stores server startup configuration.
  • package.json: The project depends on the configuration file.

Configure middleware

Configure the middleware in theapp.js file. The following are commonly used configurations:

Template Engine

In this project, ejs is used as the template engine. We can find the HTML template in the views folder.

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

Logger

Logging middleware is used to log request and response details.

app.use(logger('dev'));

Parse JSON Request Body

Parse JSON middleware is used to parse JSON data in the request body.

app.use(express.json());

Parse URL-Encoded Request Body

Parse URL encoding middleware is used to parse URL encoding data in the request body.

app.use(express.urlencoded({
    
     extended: false }));

Parse Cookie

The parsing cookie middleware is used to parse the cookie data in the request.

app.use(cookieParser());

Static Resource Middleware

Static resource middleware sets the root directory of static resources.

app.use(express.static(path.join(__dirname, 'public')));

Route Configuration

Mount the routing module and hand over the request to the corresponding route for processing.

app.use('/', indexRouter);
app.use('/users', usersRouter);

Error Handling

Catch the 404 error and forward it to the error handler, rendering the error page.

app.use(function(req, res, next) {
    
    
  next(createError(404));
});

app.use(function(err, req, res, next) {
    
    
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {
    
    };

  res.status(err.status || 500);
  res.render('error');
});

The above are examples of using Express to create static resource servers and commonly used middleware. Through these configurations, we can complete a basic back-end project skeleton, and can use other middleware to implement more functions, such as logging, error handling, etc.

Guess you like

Origin blog.csdn.net/2301_78784268/article/details/131983781
Recommended