preface

In an Internet application, the back-end server plays a very important role. Before Node.js came along, JAVASCRIPT parsing had to depend on the browser, and the back-end server had little to do with it. Thanks to Node.js, javascript is taken out of the browser, and it also has the ability to write back-end servers. In this article, we’ll talk about Express, a framework for building back-end servers using JavaScript. I’d like to break this topic down into two main sections:

  • The network server concept is related
  • The node and express

What is a Web server?

A Web server can refer to either hardware or software, or the whole of them working together.

The hardware part of a web server refers to a computer that provides network services and various resource files (such as HTML documents, JS files, CSS files, and other static resources) that make up a website. The software part of a web server refers to the application that at least provides web services. It includes several parts that control how web users access managed files. Understand Uniform Resource Locator (URL) and resolve HyperText Transfer Protocol (HTTP). Hypertext transfer Protocol) as AN HTTP server (there are many types of servers implied here, such as TCP servers, UDP servers, and so on). The server used in this article is the HTTP server.

About the network server, also need to understand its classification, it is divided into static server and dynamic server.

  • Static Web server: Returns the files it hosts to the browser’s server as they are. The process of getting resources from the static server can be understood as the process of getting goods from the warehouse. What the goods in the warehouse are, what the user gets
  • Dynamic Web Server: It consists of two parts, the static server and an additional piece of software. The function of the software is to repackage the resources in the static server, and then generate new resources to return to the client.

Workflow of web applications

As shown in the figure, a complete Web application consists of a client and a server.Any Web application starts with an HTTP request from the client. After receiving the HTTP request, the server tells the requested data to the Web application, which processes it. The application uses data from the database to convert HTML templates into HTML files that can be returned to the client, parsed and displayed by the browser. Where the application is the server-side code. In a front-end separated application, the server code is divided into two parts, the front end and the back end. The front-end code is responsible for resource integration, HTML page rendering, dynamic design, etc. The back-end code is responsible for the CRUD operations of the database, as well as other business.

nodeJS v.s. express

In this section, let’s look at the relationship between javascript, Node.js, and Express. Simply put, Node.js is a tool that allows javascript to run on the server, or it can be understood as a platform for parsing the javascript language. Express is a framework for node.js to build back-end servers. In other words, the latter two are essentially javascript. Next, I will be a porter to carry the introduction of node and Express in the MDN document:

  • The node:

Node (formally named Node.js) is an open source, cross-platform runtime environment that allows developers to create a variety of server-side tools and applications using JavaScript. This runtime is primarily used outside the browser context (that is, it can run directly on the computer or server operating system). Accordingly, the environment omits some browser-specific JavaScript apis while adding support for more traditional OS apis, such as HTTP libraries and file system libraries.

  • Express:

Express, the most popular Node framework, is the underlying library for many other popular Node frameworks. It provides the following mechanisms:

1. Write handlers for requests (routes) that use different HTTP verbs in different URL paths. 2. Integrated "View" rendering engine to generate responses by inserting data into templates. 3. Set common Web application Settings, such as the port to connect to and the location to render the response template. 4. Add additional request processing "middleware" anywhere in the request processing pipeline.Copy the code

Express Server setup

Install express library

To build a Web service application using Express, the first step should be to install the Express library:

// Add express to dependency list NPM install express --save // Temporarily install Express without adding it to dependency list NPM install express --no-saveCopy the code

The first Express application

Without further ado, just post the code:

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 at http://localhost:${port}`)})Copy the code

This code does the following:

  1. Create an Express application
  2. Bind the service to port 3000 so that the service can be accessedhttp://loaclhost:3000At this address, you can get the corresponding application
  3. Added a route so that when accessing the root path, you can see “Hello World” on the browser page

This code really does have all the elements in it. Const express=require(‘express’); const express=require(‘express’); The second line of code, const app=express(), calls the express() function, creating an express application; We then bind the app to port 3000 with app.linson() and add an app.get() method to the app that returns “Hello World” when accessing the root path.

This section describes common express methods

  1. express():

    For express(), the official documentation is as follows:

    Creates an Express application. The express() function is a top-level function exported by the express module.

    By convention, usually useexpress()Function to create an application namedapp.

  2. aplication

    appObject is called byexpress()Function. The object’s methods are used to:
    • Routing HTTP requests
    • Configuring middleware
    • Render HTML view
    • Registering the Template Engine

    In actual projects, common methods are as follows:

    • App. Listen (port, the callback) :

    Listens a UNIX socket and connections on the given path. This method is identical to the Node’s http.Server.listen().

    • App. Get (path, the callback, the callback]) :

    Routes HTTP GET requests to the specified path with the specified callback functions.

    • App. Post (path, the callback, the callback]) :

    Routes HTTP POST requests to the specified path with the specified callback functions.

    • App. Use ((path), the callback, [callback]) :

    Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.

  3. request

    reqThe object represents an HTTP request and has attributes like the request Query string, parameters, body, HTTP request, and so on. Commonly used attributes:
    • req.body
    • req.cookie
    • req.query
  4. response

    resObject represents the HTTP response and can passres.send()Method returns the response. There are two commonly used methods:
    • Res.send (): Returns an HTTP response
    • Res.status (): Set to return the corresponding status
  5. router

    The router object is a router object. The router object is a router object.

    A router object is an isolated instance of middleware and routes. You can think of it as A “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router. A router behaves like middleware itself, So you can use it as an argument to app. Use () or as the argument to another router’s use() method. The top-level express Object has a Router() method that creates a new Router object. Once you’ve created a Router object, you can add middleware and HTTP method routes (such as get, put, post, and so on) to it just like an application. For example:

reference

  • MDN documentation for Node and Express
  • MDN Describes the server
  • Express API official documentation