Introduction to the Express Framework

Table of contents

1 Introduction

1.1 Web application

1.2 API

1.3 Performance

1.4 Framework

2. How to start the Express programming journey

3. Test case

4. Other issues

4.1 How to define the model?

4.2 Which template engines does Express support?

4.3 How to handle 404 response?

4.4 How to set error handler?

 4.5 How to render plain HTML?


1 Introduction

Express is a fast, standalone, and minimal Node.js web framework. It is mainly reflected in the following aspects:

1.1 Web application

Express is a minimal and flexible Node.js web application framework that provides a powerful set of features for web and mobile applications.

1.2 API

With a myriad of HTTP utility methods and middleware at your disposal, creating powerful APIs is quick and easy.

1.3 Performance

Express provides a thin layer of basic web application functionality without obscuring the Node.js functionality you know and love.

1.4 Framework

Many popular frameworks are based on Express.

The following popular Node.js frameworks are all built on Express:

  • Feathers : Build prototypes in minutes and production-ready live applications in days.
  • ItemsAPI : A search backend for web and mobile applications built on Express and Elasticsearch.
  • KeystoneJS : Website and API application framework/CMS with auto-generated React.js admin UI.
  • Poet : Lightweight Markdown blogging engine with instant pagination, tags and category views.
  • Kraken : A secure and extensible layer that extends Express by providing structure and conventions.
  • LoopBack : A highly scalable open-source Node.js framework for quickly creating dynamic end-to-end REST APIs.
  • Sails : An MVC framework for Node.js for building practical, production-ready applications.
  • Hydra-Express : Hydra-Express is a lightweight library that facilitates building Node.js microservices using ExpressJS.
  • Blueprint : A SOLID framework for building APIs and backend services
  • Locomotive : A Powerful MVC Web Framework for Node.js by Passport.js Developers
  • graphql-yoga : A full-featured, yet simple and lightweight GraphQL server
  • Express Gateway : A full-featured and extensible API gateway based on Express
  • Dinoloop : Rest API application framework based on typescript and dependency injection
  • Kites : Template-based web application framework
  • FoalTS : An elegant and all-encompassing Node.Js web framework based on TypeScript.
  • NestJs : A progressive Node.js framework for building efficient, scalable and enterprise-grade server-side applications on top of TypeScript JavaScript (ES6, ES7, ES8)
  • Expressive Tea : A small framework for building modular, clean, fast and declarative server-side applications out of the box.

2. How to start the Express programming journey

3 The prerequisite is that Node.js must be installed in the local environment. If it is not installed, you can refer to this article: Node.js installation

Create a directory locally as the working directory.

$ mkdir myapp
$ cd myapp

 Initialize through npm init, and a package.json file will be generated in the directory.

npm init

 Follow the prompts, enter the corresponding information, and press the Enter key to enter the next entry. If it is the default, you can directly press the Enter key. As shown below:

The corresponding field information includes the following:

package name: package name

version: package version

description: Package description information, let others know what your package does.

entry point: entry file

test command: test command

git repository: git warehouse address

keywords: keywords

author: the author of the package

license: (ISC) The license defaults to ISC. The ISC license is an open source license that is functionally identical to the two-sentence version of the BSD license

Now, let's install express in the project dependencies:

$ npm install express

 After the installation is complete, check the corresponding directory below:

The package.json file has been created, and the express dependency has been installed. The corresponding version is 4.18.2. In the package.json, the entry file is specified as index.js, so create an index.js file now.

3. Test case

Write an example code in index.js, as follows:

const express = require('express')
const app = express()
const port = 3000

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

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

We first introduce the express package, set the port to 3000, the app.get route accepts 2 parameters, the first is the address, "/" is the root directory, req is the request object, res is the response object, and res.send inputs to the page content, and finally app.listen is the listening port, and the function is the parameter printed after listening.

Run the following code as follows:

node .\index.js

In the browser, we can enter http://localhost:3000/ to see the page input results:

 

 It is found that the corresponding route is found, and the content inside is printed. If we enter an undefined route address, look at the result, for example, enter: http://localhost:3000/test

 We found that the corresponding route was not found, and the page displayed 404 Not Found.

4. Other issues

4.1 How to define the model?

Express has no concept of a database. This concept is left to third-party Node modules that allow you to interact with almost any database.

See LoopBack for a model-centric Express-based framework  .

4.2 Which template engines does Express support?

Express supports any  (path, locals, callback) template engine that conforms to the signature. To standardize template engine interfaces and caching, see  the consolidate.js  project for support. Template engines not listed may still support Express signing.

4.3 How to handle 404 response?

In Express, 404 responses are not the result of errors, so the error handler middleware doesn't catch them. This behavior is because a 404 response simply means that there is no more work to do; that is, Express ran through all the middleware functions and routes and found no response. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle 404 responses:

app.use((req, res, next) => {
    res.status(404).send("不好意思,没有找到对应路径,请重新输入!")
})

 Dynamically add routes on the instance at runtime  express.Router() so routes are not replaced by middleware functions.

4.4 How to set error handler?

You can define error-handling middleware in the same way as other middleware, except with four parameters instead of three; specifically the signature  (err, req, res, next):

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
//   res.send('Hello World!')
throw Error('this is error !')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

app.use((req, res, next) => {
    res.status(404).send("不好意思,没有找到对应路径,请重新输入!")
})

app.use((err, req, res, next) => {
    console.error(err.stack)
    res.status(500).send('报错了......')
  })

We output an error in the route, then the middleware intercepts it, and then gives the corresponding prompt. The test is as follows, enter in the browser: http://localhost:3000/ as shown below:

 4.5 How to render plain HTML?

You do not need! No need to use  res.render() the function "render" HTML. If you have a specific file, use  res.sendFile() a function. If you serve many resources from a directory, use  express.static() middleware functions.

const express = require('express')
const path = require("path")
const app = express()
const port = 3000

app.use(express.static(path.join(__dirname, 'static')))
app.get('/', (req, res) => {
    // res.sendFile("D:\\2023\\code_test\\myapp\\static\\index.html")
    res.sendFile("index.html")
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

app.use((req, res, next) => {
    res.status(404).send("不好意思,没有找到对应路径,请重新输入!")
})

app.use((err, req, res, next) => {
    console.error(err.stack)
    res.status(500).send('报错了......')
  })

 res.sendFile() can return the specified file, and an absolute path is passed in by default.

You can use  express.static() middleware functions to specify the directory of static files.

Guess you like

Origin blog.csdn.net/u014388408/article/details/131748496