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.

Example:

app.set("age".18)
Copy the code

2. app.get(name)

Gets the value of the setting item name.

Example:

app.get("age")
/ / = > 18
Copy the code

3. app.enable(name)

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

Example:

app.enable("isopen")
app.get("isopen")
// => true
Copy the code

4. app.disable(name)

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

Example:

app.disable("isopen")
app.get("isopen")
// => false
Copy the code

5. app.enabled(name)

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

Example:

app.enabled("isopen")
Copy the code

6. app.disabled(name)

Check whether the value of name is false.

Example:

app.disabled("isopen")
Copy the code

7.app.listen()

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

Example:

app.listen(3000)
Copy the code

8.app.use()

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.

Example:

app.use(function(req,res,next){
    console.log("req.method ->",req.method)
    next()
})
Copy the code

Request the relevant API

Here are some common apis for requests.

1.req.params

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 req.param.id, which defaults to {}. The corresponding API is req.param(name), which returns the value of the corresponding name parameter.

2.req.query

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

3.req.body

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

4.req.route

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:

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

4.req.cookies

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

5.req.get(field)

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 “).

6.req.accepts(types)

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

7.req.is(type)

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

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

Other apis, such as req.is returns the remote address, req.path returns the path name of the requested URL, req.host 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.

1.res.status(code)

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

res.status(403).end()
res.status(400).send(Bad Request)
res.status(404).sendFile("/images/404.png")
Copy the code

2.res.set(field,[value])

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

res.set("Content-Type"."text/plain")
res.set({
    "Content-Type":"text/plain"."Content-Length":"123"."ETag":"12345"
})
Copy the code

3.res.get(field)

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

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

4.res.cookie(name,value,[options])

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:".baidu.com".path:"/index".secure:true})
res.cookie("cart", {items: [1.2.3]})
Copy the code

5.res.clearCookie(name,[options])

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

6.res.redirect([status],url)

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(“baidu.com “). In the second case, the res.redirect(“/detail”) is directed to “example.com/detail “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 “example.com/products/de… Res.redirect (“back”) will redirect to the referer address, which defaults to/when the referer is lost.

7.res.send([body|status],[body])

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.

8.res.json([status|body],[body])

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”})

9.res.format(object)

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

res.format({
    "text/plain":function(){
        res.send("hi")},"text/html":function(){
        res.send("hey")},"application/json":function(){
        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:

app.use("/index",router)
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:

router.all("*",requireAuthentication,loadUser)
Copy the code

Only applies to paths starting with API:

router.all("/api/*",requireAuthentication)
Copy the code

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

Router.get (), router.put(), router.post(), 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:

router.get("/".function(req,res){
    res.send("hello world")})Copy the code

3.router.param(name,callback)

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:

router.param("id".function(req,res,next,id){
    console.log("called only once")
})
router.get("/user/:id".function(req,res,next){
    console.log("although this matches")
    next()
})
router.get("/user/:id".function(req,res){
    console.log("and this matches too")
    res.end()
})
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

4.router.route(path)

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 = {
        id:id,
        name:"TJ"
    };
    next();
});
router.route('/users/:user_id')
    .all(function(req, res, next) {
        next();
    })
    .get(function(req, res, next) {
        res.json(req.user);
    })
    .put(function(req, res, next) {
        req.user.name = req.params.name;
        res.json(req.user);
    })
    .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.

Reference:

Express Chinese document

Novice tutorial