Moment For Technology

Express the API to summarize

Posted on Dec. 1, 2022, 12:36 p.m. by Annette Holland
Category: The front end Tag: express api

Recently, I have learned Express. Here, I will briefly summarize it from app related API, Request related API, Response related API and Router related API.

Express is a Node framework, so you must download Node and then the Express framework before you can use it.

NPM install express --save

Express () creates the application

Express () is the entry function exported by the Express module to create an Express application.

var express = require('express');

var app = express();

Copy the code

App related API

As shown above, APP is an Express application created with a number of apis, which are described below.

1. app.set(name,value)

Use to set the value of the Settings item name to value.


Copy the code

2. app.get(name)

Gets the value of the setting item name.


/ / =  18
Copy the code

3. app.enable(name)

Use to set the value of the setting item name to true.


// = true
Copy the code

4. app.disable(name)

Use to set the value of the setting item name to false.


// = false
Copy the code

5. app.enabled(name)

Check whether the value of the setting item name is true.


Copy the code

6. app.disabled(name)

Check whether the value of name is false.


Copy the code

Listening for requests on a given host and port can handle both HTTP and HTTPS versions of the service.


Copy the code

For express-related middleware, as shown in the following example, where the mounted path does not appear in the REq and is not visible to the middleware function, this means that the path is not found in the callback parameter req. This is designed so that the middleware does not need to change the code to execute under any prefixed path.


    console.log("req.method -",req.method)
Copy the code

Request the relevant API

Here are some common apis for requests.


This is an array object, and the named parameters are stored as key-value pairs. If there is a route /user/:id, the "id" attribute is stored in, which defaults to {}. The corresponding API is req.param(name), which returns the value of the corresponding name parameter.


This is a parsed request parameter object, which defaults to {}. If there is a route /detail/id=123, then the value of is 123.


This is the parsed request body, which defaults to {}.


This object contains the attributes contained in the currently matched Route, including the original path string, generated re, method, query parameters, and so on. Example:

// The output is:
{ path: '/user/:id? '.method: 'get'.callbacks: [[Function]],keys: [{name: 'id'.optional: true}].regexp: /^/user(? :/ [^ /] +? )? /? $/i,params: [ id: '12']}Copy the code


With the cookieParaser() middleware, this object defaults to {} and also contains cookies from the user agent.


Retrieves the value of the field in the request header. Note that the referrer and referer fields are interchangeable. For example the req. Get (" the content-type ").


Check if the types given are Acceptable, and return the most Acceptable if they are Acceptable, otherwise return undefined, which should respond with a 406 "Not Acceptable" response. Example:

// Accept:text/html
req.accepts("html")  // "html"
// Accept:text/*,application/json
req.accepts("html")  // "html"
req.accepts("text/html")  // "text/html"
req.accepts("json,text")  // "json"
req.accepts("image/png")  // undefined
req.accepts("png")  // undefined
Copy the code

Check if the request header contains the "Content-Type" field, which matches the given Type.

/ / the content-type: text/HTML"html")  //true"text")  //true"text/html")  //true"json")  //false"application/json")  //false
Copy the code

Other apis, such as returns the remote address, req.path returns the path name of the requested URL, returns the host name from the "host" header without the port number, and req.protocol returns a string representing the request protocol. This is usually "HTTP", but "HTTPS" is returned when a TLS request is made.

The response related API

Some response related apis are displayed below.


To set the HTTP status of the response, this is a chained call to Node's Response. statusCode. Example:

res.status(400).send(Bad Request)
Copy the code


Set the response header field value to value. You can also set multiple values by passing in an object at a time. Example:

Copy the code


Returns the value of a case-insensitive field in the response header. Example:

res.get("Content-Type")  // "text/plain"
Copy the code


Set cookie name to value and accept either a string parameter or a JSON object. The default path attribute is "/". Example:

res.cookie("name"."mary", {domain:"".path:"/index".secure:true})
res.cookie("cart", {items: [1.2.3]})
Copy the code


Clear cookie for name, default path to "/". Such as res. ClearCookie (" name ", {path: "/ index"})


Use the optional status code to jump to the URL. The default status code is 302 "Found". Express supports several kinds of redirects. First, use a complete URL to redirect to a completely different website, such as res.redirect(" "). In the second case, the res.redirect("/detail") is directed to " "relative to the root domain. The third is the pathname redirect, res.redirect("..") ) is to jump to the next level of the page, such as the current " Res.redirect ("back") will redirect to the referer address, which defaults to/when the referer is lost.


Send a response. This method automatically does a lot of useful things when it outputs the response, such as defining the undefined content-length, adding some automatic HEAD, and so on. When the argument is a Buffer, the content-type is set to "application/octet-stream". When the argument is a String, the content-type is set to "text/ HTML "by default. When an Array or Object is used, Express returns a JSON. When a Number is used, Express automatically sets a response body. For example, 200 returns the character "OK", 404 returns "Not Found", etc.


Return a JSON response. Res.send () is called when the parameter is an object or array. It is useful for complex JSON conversions with null,undefined,etc values. Res.json (null), res.json({user:" Mary "}), res.json(500,{error:"message"})


If there is no match, the server will return a 406 "Not Acceptable" or perform a default callback. Example:

        res.send({message:"boy"})}})Copy the code

This code returns "{message:'boy'}" when the request header is "application/json" or "*/json".

Other apis, such as res.locals, provide local variables for the body of a request, which are only visible to views during the request, as is provided by app.locals. Res.render (view,[locals],callback) renders the view, passing the rendered string to the callback.

The router related API

A Router object is a single instance, thought of as a "mini-application", with the ability to manipulate middleware and routing methods. Each Express program has a built-in APP route, and the route itself represents a middleware. So you can use it as an argument to the app.use() method or as an argument to the use() of another route. Create a route:

var router = express.Router([options])
Copy the code

You can hang a route on a particular root URL, so you can put each route in a different file. Example:

Copy the code

1.router.all(path,[callback,...] callback)

Matches all HTTP actions, which is useful for mapping global logic to special path prefixes or arbitrary matches, such as validation of all routes from a certain point and automatic loading of user information, as shown in the following example:

Copy the code

Only applies to paths starting with API:

Copy the code

2.router.method(path,[callback,...] callback)

Router.get (), router.put(),, and so on can be used in the same way as router.all(). Regular expressions can also be used if there are special restrictions on the matching path. Example:

    res.send("hello world")})Copy the code


Add a callback trigger to the route parameter, name refers to the parameter name, function is the callback method, the parameters of the callback method are the request object, the response object, the next middleware, the parameter value and the parameter name, for the route defined by param's callback, they are local, not inherited by the mounted app or route. Therefore, the param callback defined on the router takes effect only if the route on the router has the route parameter. On routes where param is defined, the param callback is called first, and they are called once and only once in a request-response loop, even if multiple routes match. Example:

    console.log("called only once")
    console.log("although this matches")
    console.log("and this matches too")
Copy the code

When GET /user/43, the following result is obtained:

called only once
although this matches
and this matches too
Copy the code


Middleware that returns an instance of a singleton pattern route on which various HTTP actions can later be applied. Example:

router.param('user_id'.function(req, res, next, id) {
    req.user = {
    .all(function(req, res, next) {
    .get(function(req, res, next) {
    .put(function(req, res, next) { =;
    .post(function(req, res, next) {
        next(new Error('not implemented'));
    .delete(function(req, res, next) {
        next(new Error('not implemented'));
Copy the code

5.router.use([path],[function,...] function)

Mount the given middleware method to the path specified with the optional path parameter. If path is not specified, the default is /, similar to the app.use() method.


Express Chinese document

Novice tutorial

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.