This is the second day of my participation in the August Text Challenge.More challenges in August

Lynne, a front-end development engineer who can cry, love and laugh forever. In the Internet wave, love life and technology.

note-express

Express the API to summarize

Start by creating an express application instance. The Express () function is a top-level function around the Express module.

var express = reqiure('express')
var app = express()
Copy the code

Express API

  1. express.json([options])

Expression () is a built-in middleware function for Express that uses body-Parser to parse incoming requests with JSON payload.

That is, it parses the incoming JSON data and returns an object, with an error if invalid.

Parameters of the options

  • inflate
  • Limit – Controls the maximum request size
  • Riviver – Passes directly to JSON
  • Strict – Enables or disables accepting only arrays and objects; When disabled, any JSON will be accepted, parse received
  • Type – Used to determine what media types will the middleware parse
  • verify

To illustrate:

var express = require('express'); 
var app = express(); 
var PORT = 3000; 
  
// Without this middleware 
// app.use(express.json()); 
app.post('/'.function (req, res) { 
    console.log(req.body.name) 
    res.end(); 
}) 
  
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
});
Copy the code

You can see what express.json() does by running Node index.js and watching the console output with and without express.json().

  1. express.raw([options])

This is a middleware feature built into Express. The incoming request payload is parsed to Buffer based on body-parser.

This middleware parses all principals into buffers and only looks at requests whose Content-Type headers match the Type option. The parser accepts any Unicode encoding for the body and supports automatic bloating of gZIP and Deflate encodings.

After middleware (such as req.body), a new body Buffer containing parsed data is populated on the request object, or an empty object ({}) if there is no body to parse, the Content-Type does not match, or an error occurs.

Parameters of the options

  • inflate
  • Limit – Controls the maximum request size
  • Type – Used to determine what media types will the middleware parse
  • verify
  1. express.Router([options])

Create a native Router object.

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

Parameters of the options

  • CaseSensitive – caseSensitive, false by default
  • MergeParams – Subarguments take precedence. Default is false
  • Strict – Strict mode routing
  1. express.static(root, [options])

Express built-in middleware, serve-static service for static files

The root parameter specifies the root directory that provides static resources. This function combines req to determine the file to serve. The Url with the supplied root directory. Instead of sending a 404 response when no file is found, it calls next() to move on to the next middleware, allowing stacking and fallback.

Parameters of the options

  • setHeaders
  • etag
  • redirect
  • lastModified
  • maxAge
  • immutable
  • redirect
  1. express.text([options])

The built-in middleware in Express parses the incoming request payload into a string based on Body-Parser.

  1. express.urlencoded([options])

The middleware built into Express, body-parser based, uses a URL-encoded payload to parse incoming requests.

2, Application related API

App objects typically represent Express applications. It is created by calling the top-level Express () function exported by the Express module:

var express = reqiure('express')
var app = express()

app.get('/'.function (req, res) = >{
    res.send('hello, Lynne')
})

app.listen(3000)
Copy the code

App object methods:

  • Routing HTTP requests; For example, app.method and app.param.
  • Configure middleware; See the app. The route.
  • Render HTML view; See the app. Render.
  • Register the template engine; See the app engine.

It also has Settings (properties) that affect the behavior of the application.

The properties of the app.local-locals object are local variables in the application.

Once set, the value of the app.locals property remains constant for the lifetime of the application, whereas the res.locals property is only available for the lifetime of the request. The ability to access local variables in templates rendered in applications is useful for providing helper functions and application-level data to templates. Local variables are available from the middleware via req.app.locals.

App.mountpath – Contains one or more path modes for mounting child applications. Focus on patterns, not paths!

var admin = express()

admin.get('/'.function (req, res) {
  console.dir(admin.mountpath) // [ '/adm*n', '/manager' ]
  res.send('Admin Homepage')})var secret = express()
secret.get('/'.function (req, res) {
  console.log(secret.mountpath) // /secr*t
  res.send('Admin Secret')
})

admin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n'.'/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app
Copy the code
  1. App.on (‘mount’, callback(parent)) – Event that will trigger the mount event on the child app when it is mounted to the parent app. The parent application is passed to the callback function.
var admin = express()

admin.on('mount'.function (parent) {
  console.log('Admin Mounted')
  console.log(parent) // refers to the parent app
})

admin.get('/'.function (req, res) {
  res.send('Admin Homepage')
})

app.use('/admin', admin)
Copy the code
  1. app.all(path, callback [, callback …] ) – Similar to app.method (), but it matches all request methods.

Path-path string/path-matching pattern/combination array callback – Middleware function/family of middleware functions/middleware array/combination

app.all('/secret'.function (req, res, next) {
  console.log('Accessing the secret section ... ')
  next() // pass control to the next handler
})
Copy the code

The app.all() method is useful for mapping “global” logic to specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, you would require that all routes from that point on require authentication and automatically load users. Keep in mind that these callbacks don’t have to act as endpoints :loadUser can perform a task and then call next() to continue matching subsequent routes.

  1. app.delete(path, callback [, callback …] ) – routes HTTP DELETE requests to the specified path using the specified callback function.

Corresponding to HTTP DELETE request

  1. App.get (name) – Returns the value of the name application setting, where name is one of the strings in the application Settings table.

  2. app.get(path, callback [, callback …] ) – routes HTTP GET requests to the specified path using the specified callback function.

app.get('/'.function (req, res) {
  res.send('GET request to homepage')})Copy the code
  1. App.listen (Path, [callback]) – Starts a UNIX socket and listens for connections on a given path. This method is the same as http.server.listen () for Node.
var express = require('express')
var app = express()
app.listen('/tmp/sock')
Copy the code
  1. App.listen ([port[, host[, backlog]]]][, callback]) – Binds and listens for connections on the specified host and port. This method is the same as http.server.listen () for Node.

If port is omitted or 0, the operating system will assign an arbitrary unused port, which is useful for situations such as automated tasks (tests, etc.).

var express = require('express')
var app = express()
app.listen(3000)
Copy the code

The application returned by Express () is actually a JavaScript function designed to be passed as a callback to Node’s HTTP server to handle the request. This makes it easy to provide the HTTP and HTTPS versions of the application using the same code base, because the application doesn’t inherit these (it’s just a callback):

Var express = require('express')
Var HTTPS = require(' HTTPS ')
Var HTTP = require(' HTTP ')
Var app = express()

http.createServer (app) .listen (80) HTTPS. CreateServer (options, programs).listen (443)
Copy the code

The app.listen() method returns an HTTP server object and (for HTTP) is a handy method as follows:

app.listen = function () {
  var server = http.createServer(this)
  return server.listen.apply(server, arguments)}Copy the code
  1. app.METHOD(path, callback [, callback …] ) – Routes HTTP requests. METHOD is the HTTP METHOD of the request, such as GET, PUT, and POST. So the actual methods are app.get(), app.post(), app.put(), and so on.

There are only explicit entries in the API documentation for the most popular HTTP methods app.get(), app.post(), app.put(), and app.delete(). However, the other methods listed above work in exactly the same way.

To route methods that convert to invalid JavaScript variable names, use the parenthesis notation. For example, app[‘m-search’](‘/’, function….

  1. App.param ([name], callback)- Adds a callback trigger to the route parameters, where name is the parameter name or parameter array and callback is the callback function.

The arguments to the callback function are, in order, the request object, the response object, the next middleware, the value of the parameter, and the name of the parameter.

If name is an array, then the callback triggers are registered for each parameter declared in it in the declared order. In addition, for each declared parameter except the last, calling next in the callback invokes the callback of the next declared parameter. For the last parameter, the call to Next calls the next middleware of the route currently being processed, as if name were just a string.

  1. App.path () – Returns the canonical path to the application, a string.
var app = express()
var blog = express()
var blogAdmin = express()

app.use('/blog', blog)
blog.use('/admin', blogAdmin)

console.dir(app.path()) / /"
console.dir(blog.path()) // '/blog'
console.dir(blogAdmin.path()) // '/blog/admin'
Copy the code

In complex cases of installing applications, the behavior of this method can become very complex, and it is often better to use req.baseurl. To get the canonical path to the application.

  1. app.post(path, callback [, callback …] ) – routes HTTP POST requests to the specified path using the specified callback function.

  2. App.render (view, [locals], callback) – Returns the HTML rendered by the view via the callback function. It takes an optional argument, which is an object containing view local variables. It is similar to res.Render (), except that it cannot send the rendered view to the client itself.

You can think of app.render() as a utility function for generating render view strings. Internally res.render() uses app.render() to render the view.

  1. App.route (path) – Returns an instance of a single route, which can then be used.
var app = express()

app.route('/events')
  .all(function (req, res, next) {
    // runs for all HTTP verbs first
    // think of it as route specific middleware!
  })
  .get(function (req, res, next) {
    res.json({})
  })
  .post(function (req, res, next) {
    // maybe add a new event...
  })
Copy the code
  1. App.set (name, value) – Sets the name assignment.

You can store any desired value, but certain names can be used to configure the behavior of the server. These special names are listed in the application Settings table.

Calling app.set(‘foo’, true) for Boolean properties is the same as calling app.enable(‘foo’). Similarly, calling app.set(‘foo’, false) for a Boolean property is the same as calling app.disable(‘foo’).

Use app.get() to get the value of the setting.

  1. app.use([path,] callback [, callback…] ) – important!

Mount the specified middleware functionality to the specified path: When the base of the requested path matches the path, the middleware functionality is executed.

Error-handling middleware

Error-handling middleware always has four parameters. You must provide four parameters to identify it as an error-handling middleware function. Even if you do not need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will not be able to handle errors.

Define error-handling middleware functions in the same way as other middleware functions, except that four arguments are used instead of three, specifically using signatures (err, REq, RES, next):

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke! ')})Copy the code