This is the third 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.

Request related API

A REQ object represents an HTTP request and has properties such as request query string, parameters, body, HTTP, and so on. In this document, by convention, the object is always referred to as REQ (the HTTP response is RES), but its actual name is determined by the arguments to the callback function you are using.

The request object has more properties and apis that are easier to understand. Select a few more important records.

  1. Req.app – This property holds a reference to an Express application instance that is using middleware.

If you follow the pattern of creating a module, exporting only one middleware function and requiring () it in the main file, then the middleware can access the Express instance through req.app

  1. Req.body – The key-value pair data submitted in the request body.

By default, it is undefined and populated when body parsing middleware such as express.json() or express.urlencoded() is used.

  1. Req. cookies – When using cookie-parser middleware, this property is an object that contains cookies sent by the request. If the request does not contain cookies, it defaults to {}.

  2. req.method

  3. req.originalUrl

  4. req.query

This property is an object containing properties for each query string parameter in the route. When the query parser is set to Disabled, it is an empty object {}, otherwise it is the result of a configured query parser.

  1. Req. route – Contains the current matched route, a character string.

  2. Req.get (field) – Returns the specified HTTP request header field (case insensitive). The Referrer and Referer fields are interchangeable.

Iv. Response-related apis

The RES object represents the HTTP response that an Express application sends when it receives an HTTP request.

  1. Res.append (field [, value]) – Appends the specified value to the HTTP response header field.

If the header is not already set, it creates the header with the specified value. The value argument can be a string or an array.

Note: Calling res.set() after res.append() resets the previously set header value.

  1. Res. cookie(name, value [, options]) – Sets the cookie name to value. The value argument can be a string or object converted to JSON.

The options argument is an object that can have the following properties:

domian – expires – path – httpOnly –

  1. Res.end ([data] [, encoding]) – Ends the response.

This method actually comes from the Node core, specifically the response.end() method of http.serverResponse.

Used to quickly end a response without any data. If you need to respond with data, use methods like res.send() and res.json().

  1. Res.get (filed) – Returns the HTTP response header specified by the field. Matching is case insensitive.

  2. Res.json ([body]) – Sends a JSON response.

This method sends a response (with the correct content type) that is converted to a JSON string parameter using json.stringify ().

This parameter can be any JSON type, including an object, array, string, Boolean, number, or NULL, and you can also use it to convert other values to JSON.

  1. Res.render (View [, locals] [, callback]) – Renders the view and sends the rendered HTML string to the client.

Optional parameters:

A local variable object whose properties define local variables for the view. Callback, a Callback function. If provided, a possible error and rendered string are returned, but no automatic response is performed. This method internally calls Next (err) when an error occurs. The view argument is a string that is the file path of the view file to render. This can be an absolute path or a path set relative to the view. If the path does not contain the file extension, the view engine Settings determine the file extension. If the path does contain a file extension, Then Express loads the module for the specified template engine (via require()) and renders it using the __express function that loads the module.

  1. Res.redirect ([status,] path) – Redirect to the URL derived from the specified path with the specified state, which is a positive integer corresponding to the HTTP status code. If not specified, status defaults to “302” Found.

  2. Res.send ([body]) – Sends an HTTP response.

The body argument can be a Buffer, a String, an object, a Boolean, or an array.

5. Router related apis

  1. router.all(path, [callback, …] Callback) – matches all HTTP methods, similar to app.all

This METHOD is similar to the router.method () METHOD, except that it matches all HTTP methods (verbs).

This method is useful for mapping specific path prefixes or “global” logic for any match. For example, if you put the following route at the top of all other route definitions, it would require that all routes from that point on require authentication and automatically load a user. Remember 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. Router.route (Path) – Returns an instance of a single route that can then be used to process HTTP methods with optional middleware.

Use router.route() to avoid repeating route names, thus avoiding typing errors.

Based on the router.param() example above, the following code shows how router.route() can be used to specify various HTTP method handlers.

var router = express.Router()

router.param('user_id'.function (req, res, next, id) {
  // sample user, would actually fetch from DB, etc...
  req.user = {
    id: id,
    name: 'TJ'
  }
  next()
})

router.route('/users/:user_id')
  .all(function (req, res, next) {
    // runs for all HTTP verbs first
    // think of it as route specific middleware!
    next()
  })
  .get(function (req, res, next) {
    res.json(req.user)
  })
  .put(function (req, res, next) {
    // just an example of maybe updating the user
    req.user.name = req.params.name
    // save user ... etc
    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
  1. router.use([path], [function, …] Function) – uses the specified middleware function, with an optional mount path path, default “/”.

This method is similar to app.use().

Middleware is like a pipeline: requests start from the first middleware function defined and work “down” the middleware stack for each path they match.

var express = require('express')
var app = express()
var router = express.Router()

// simple logger for this router's requests
// all requests to this router will first hit this middleware
router.use(function (req, res, next) {
  console.log('%s %s %s', req.method, req.url, req.path)
  next()
})

// this will only be invoked if the path starts with /bar from the mount point
router.use('/bar'.function (req, res, next) {
  // ... maybe some additional /bar logging ...
  next()
})

// always invoked
router.use(function (req, res, next) {
  res.send('Hello World')
})

app.use('/foo', router)

app.listen(3000)
Copy the code

The mount path is stripped and not visible to middleware functionality. The main impact of this feature is that mounted middleware functions can run without changing the code, regardless of the “prefix” pathname.

It is important to define the order of middleware using router.use(). They are called sequentially, so that order defines middleware priorities. For example, loggers are usually the first piece of middleware you will use, so every request will be logged.