Express urlencoded что это

EXPRESS, параметры запроса

Express urlencoded что это. Смотреть фото Express urlencoded что это. Смотреть картинку Express urlencoded что это. Картинка про Express urlencoded что это. Фото Express urlencoded что это

Разберем подробнее объект Request, что он содержит и как с ним работать.

Вот основные свойства, которые вы, вероятно, будете использовать:

СвойствоОписание
.appсодержит ссылку на объект приложения Express
.baseUrlбазовый путь, по которому приложение отвечает
.bodyсодержит данные, представленные в теле запроса (должны быть проанализированы и заполнены вручную, прежде чем вы сможете получить к ним доступ)
.cookiesсодержит данные cookie, отправленные по запросу (требуется промежуточная программная обработка cookie-parser)
.hostnameназвание сервера
.ipIP сервера
.methodиспользуемый HTTP метод
.paramsпараметры запроса в роуте
.pathURL путь
.protocolпротокол запроса
.queryобъект, содержащий все параметры запроса
.securetrue если запрос безопасен (использует HTTPS)
.signedCookiesсодержит данные cookie, отправленные запросом (требуется промежуточная программная обработка cookie-parser)
.xhrtrue если запрос отправлен с помощью XMLHttpRequest

Как получить GET параметры запроса с использованием express

Пример строки запроса:

Как нам получить эти значения из строки запроса в Express?

Express делает это очень просто, заполняя объект Request.query для нас:

Этот объект заполнен значениями для каждого параметра запроса. Если в запросе не было параметров, данный объект будет пустым.

Мы можем перебрать этот объект использовав цикл for… in:

Пример выше распечатает в консоли ключи и значения содержащиеся в объекте.

Вы также можете получить доступ к отдельным свойствам:

Как получить post query string параметры с использованием express

Параметры запроса POST отправляются клиентами HTTP, например, с помощью форм или при выполнении данных отправки запроса POST.

Как вы можете получить доступ к этим данным?

Если данные были отправлены как JSON с использованием Content-Type: application / x-www-form-urlencoded, вы будете использовать промежуточное программное обеспечение express.urlencoded ():

В обоих случаях вы можете получить доступ к данным, ссылаясь на них из Request.body:

В старых версиях Express для обработки данных POST требовалось использовать модуль body-parser. Это больше не относится к Express 4.16 (выпущенной в сентябре 2017 года) и более поздним версиям.

Источник

5.x API

Note: This is early alpha documentation that may be incomplete and is still under development.

express()

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

Methods

express.json([options])

This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.

Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty object ( <> ) if there was no body to parse, the Content-Type was not matched, or an error occurred.

As req.body ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

The following table describes the properties of the optional options object.

express.static(root, [options])

This is a built-in middleware function in Express. It serves static files and is based on serve-static.

NOTE: For best results, use a reverse proxy cache to improve performance of serving static assets.

The root argument specifies the root directory from which to serve static assets. The function determines the file to serve by combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, it instead calls next() to move on to the next middleware, allowing for stacking and fall-backs.

The following table describes the properties of the options object. See also the example below.

PropertyDescriptionTypeDefault
dotfilesDetermines how dotfiles (files or directories that begin with a dot “.”) are treated.

See dotfiles below.

String“ignore”
etagEnable or disable etag generation

See fallthrough below.

Booleantrue
immutableEnable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.Booleanfalse
indexSends the specified directory index file. Set to false to disable directory indexing.Mixed“index.html”
lastModifiedSet the Last-Modified header to the last modified date of the file on the OS.Booleantrue
maxAgeSet the max-age property of the Cache-Control header in milliseconds or a string in ms format.Number0
redirectRedirect to trailing “/” when the pathname is a directory.Booleantrue
setHeadersFunction for setting HTTP headers to serve with the file.

See setHeaders below.

Function
dotfiles

Possible values for this option are:

NOTE: With the default value, it will not ignore files in a directory that begins with a dot.

fallthrough

Set this option to true so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.

Use false if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

setHeaders

For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously.

The signature of the function is:

Example of express.static

Here is an example of using the express.static middleware function with an elaborate options object:

express.Router([options])

Creates a new router object.

The optional options parameter specifies the behavior of the router.

PropertyDescriptionDefaultAvailability
caseSensitiveEnable case sensitivity.Disabled by default, treating “/Foo” and “/foo” as the same.
mergeParamsPreserve the req.params values from the parent router. If the parent and the child have conflicting param names, the child’s value take precedence.false4.5.0+
strictEnable strict routing.Disabled by default, “/foo” and “/foo/” are treated the same by the router.

For more information, see Router.

express.urlencoded([options])

This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.

Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty object ( <> ) if there was no body to parse, the Content-Type was not matched, or an error occurred. This object will contain key-value pairs, where the value can be a string or array (when extended is false ), or any type (when extended is true ).

As req.body ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

The following table describes the properties of the optional options object.

Application

The app object conventionally denotes the Express application. Create it by calling the top-level express() function exported by the Express module:

The app object has methods for

It also has settings (properties) that affect how the application behaves; for more information, see Application settings.

Properties

app.locals

The app.locals object has properties that are local variables within the application.

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via req.app.locals (see req.app)

app.mountpath

The app.mountpath property contains one or more path patterns on which a sub-app was mounted.

A sub-app is an instance of express that may be used for handling the request to a route.

It is similar to the baseUrl property of the req object, except req.baseUrl returns the matched URL path, instead of the matched patterns.

If a sub-app is mounted on multiple path patterns, app.mountpath returns the list of patterns it is mounted on, as shown in the following example.

app.router

The application’s in-built instance of router. This is created lazily, on first access.

You can add middleware and HTTP method routes to the router just like an application.

For more information, see Router.

Events

app.on(‘mount’, callback(parent))

The mount event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.

NOTE

Methods

This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.

Arguments

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

Examples

The following callback is executed for requests to /secret whether using GET, POST, PUT, DELETE, or any other HTTP request method:

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

Another example is white-listed “global” functionality. The example is similar to the ones above, but it only restricts paths that start with “/api”:

Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the routing guide.

Arguments

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

Example

app.disable(name)

app.disabled(name)

Returns true if the Boolean setting name is disabled ( false ), where name is one of the properties from the app settings table.

app.enable(name)

app.enabled(name)

Returns true if the setting name is enabled ( true ), where name is one of the properties from the app settings table.

app.engine(ext, callback)

By default, Express will require() the engine based on the file extension. For example, if you try to render a “foo.pug” file, Express invokes the following internally, and caches the require() on subsequent calls to increase performance.

For example, to map the EJS template engine to “.html” files:

Some template engines do not follow this convention. The consolidate.js library maps Node template engines to follow this convention, so they work seamlessly with Express.

app.get(name)

Returns the value of name app setting, where name is one of the strings in the app settings table. For example:

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

Arguments

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

For more information, see the routing guide.

Example

app.listen(path, [callback])

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

app.listen([port[, host[, backlog]]][, callback])

Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().

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

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

NOTE: All the forms of Node’s http.Server.listen() method are in fact actually supported.

Arguments

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

Routing methods

Express supports the following routing methods corresponding to the HTTP methods of the same names:

For more information on routing, see the routing guide.

app.param(name, callback)

Add callback triggers to route parameters, where name is the name of the parameter or an array of them, and callback is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.

If name is an array, the callback trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to next inside the callback will call the callback for the next declared parameter. For the last parameter, a call to next will call the next middleware in place for the route currently being processed, just like it would if name were just a string.

For example, when :user is present in a route path, you may map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on app will be triggered only by route parameters defined on app routes.

All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

app.path()

Returns the canonical path of the app, a string.

The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use req.baseUrl to get the canonical path of the app.

Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the routing guide.

Arguments

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

Example

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

Arguments

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

Example

app.render(view, [locals], callback)

Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render(), except it cannot send the rendered view to the client on its own.

Think of app.render() as a utility function for generating rendered view strings. Internally res.render() uses app.render() to render views.

app.route(path)

Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).

app.set(name, value)

Application Settings

The following table lists application settings.

Note that sub-apps will:

Exceptions: Sub-apps will inherit the value of trust proxy even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of view cache in production (when NODE_ENV is “production”).

case sensitive routing

Enable case sensitivity. When enabled, «/Foo» and «/foo» are different routes. When disabled, «/Foo» and «/foo» are treated the same.

NOTE: Sub-apps will inherit the value of this setting.

StringEnvironment mode. Be sure to set to «production» in a production environment; see Production best practices: performance and reliability.

process.env.NODE_ENV ( NODE_ENV environment variable) or “development” if NODE_ENV is not set.

Set the ETag response header. For possible values, see the etag options table.

jsonp callback name

NOTE: Sub-apps will inherit the value of this setting.

NOTE: Sub-apps will inherit the value of this setting.

VariedThe ‘space’ argument used by `JSON.stringify`. This is typically set to the number of spaces to use to indent prettified JSON.

NOTE: Sub-apps will inherit the value of this setting.

The simple query parser is based on Node’s native query parser, querystring.

The extended query parser is based on qs.

A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.

Enable strict routing. When enabled, the router treats «/foo» and «/foo/» as different. Otherwise, the router treats «/foo» and «/foo/» as the same.

NOTE: Sub-apps will inherit the value of this setting.

NumberThe number of dot-separated parts of the host to remove to access subdomain.2

Indicates the app is behind a front-facing proxy, and to use the X-Forwarded-* headers to determine the connection and the IP address of the client. NOTE: X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable.

When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table.

The `trust proxy` setting is implemented using the proxy-addr package. For more information, see its documentation.

NOTE: Sub-apps will inherit the value of this setting, even though it has a default value.

String or ArrayA directory or an array of directories for the application’s views. If an array, the views are looked up in the order they occur in the array.

Enables view template compilation caching.

NOTE: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is «production»).

true in production, otherwise undefined.

StringThe default engine extension to use when omitted.

NOTE: Sub-apps will inherit the value of this setting.

Options for `trust proxy` setting

Read Express behind proxies for more information.

An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are:

Set IP addresses in any of the following ways:

Specify a single subnet:

Specify a subnet and an address:

Specify multiple subnets as CSV:

Specify multiple subnets as an array:

When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client’s IP address.

Trust the n th hop from the front-facing proxy server as the client.

Custom trust implementation. Use this only if you know what you are doing.

Options for `etag` setting

NOTE: These settings apply only to dynamic files, not static files. The express.static middleware ignores these settings.

The ETag functionality is implemented using the etag package. For more information, see its documentation.

TypeValue
Boolean

true enables weak ETag. This is the default setting.
false disables ETag altogether.

Custom ETag function implementation. Use this only if you know what you are doing.

app.use([path,] callback [, callback. ])

Arguments

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

Since router and app implement the middleware interface, you can use them as you would any other middleware function.

Description

Since path defaults to “/”, middleware mounted without a path will be executed for every request to the app.
For example, this middleware function will be executed for every request to the app:

NOTE

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

Error-handling middleware

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t 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 fail to handle errors. For details about error-handling middleware, see: Error handling.

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next) ):

Path examples

The following table provides some simple examples of valid path values for mounting middleware.

This will match paths starting with /abcd :

This will match paths starting with /abcd and /abd :

This will match paths starting with /ad and /abcd :

This will match paths starting with /abc and /xyz :

Middleware callback function examples

TypeValue
Boolean
StringIf «strong», enables strong ETag.
If «weak», enables weak ETag.
Function

You can define and mount a middleware function locally.

A router is valid middleware.

An Express app is valid middleware.

You can specify more than one middleware function at the same mount path.

Use an array to group middleware logically.

You can combine all the above ways of mounting middleware.

Following are some examples of using the express.static middleware in an Express app.

Serve static content for the app from the “public” directory in the application directory:

Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:

Disable logging for static content requests by loading the logger middleware after the static middleware:

Serve static files from multiple directories, but give precedence to “./public” over the others:

Request

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the HTTP response is res ) but its actual name is determined by the parameters to the callback function in which you’re working.

But you could just as well have:

The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods.

Properties

In Express 4, req.files is no longer available on the req object by default. To access uploaded files on the req.files object, use multipart-handling middleware like busboy, multer, formidable, multiparty, connect-multiparty, or pez.

req.app

This property holds a reference to the instance of the Express application that is using the middleware.

If you follow the pattern in which you create a module that just exports a middleware function and require() it in your main file, then the middleware can access the Express instance via req.app

req.baseUrl

The URL path on which a router instance was mounted.

The req.baseUrl property is similar to the mountpath property of the app object, except app.mountpath returns the matched path pattern(s).

Even if you use a path pattern or a set of path patterns to load the router, the baseUrl property returns the matched string, not the pattern(s). In the following example, the greet router is loaded on two path patterns.

req.body

As req.body ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

req.cookies

If the cookie has been signed, you have to use req.signedCookies.

For more information, issues, or concerns, see cookie-parser.

req.fresh

When the response is still “fresh” in the client’s cache true is returned, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent.

When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent.

Further details for how cache validation works can be found in the HTTP/1.1 Caching Specification.

req.host

Contains the host derived from the Host HTTP header.

If there is more than one X-Forwarded-Host header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.

req.hostname

Contains the hostname derived from the Host HTTP header.

If there is more than one X-Forwarded-Host header in the request, the value of the first header is used. This includes a single header with comma-separated values, in which the first value is used.

Prior to Express v4.17.0, the X-Forwarded-Host could not contain multiple values or be present more than once.

req.ip

Contains the remote IP address of the request.

req.ips

req.method

req.originalUrl

req.url is not a native Express property, it is inherited from Node’s http module.

This property is much like req.url ; however, it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes. For example, the “mounting” feature of app.use() will rewrite req.url to strip the mount point.

req.params

Any changes made to the req.params object in a middleware or route handler will be reset.

NOTE: Express automatically decodes the values in req.params (using decodeURIComponent ).

req.path

Contains the path part of the request URL.

req.protocol

req.query

As req.query ’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.query.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

req.route

Contains the currently-matched route, a string. For example:

Example output from the previous snippet:

req.secure

A Boolean property that is true if a TLS connection is established. Equivalent to the following:

req.signedCookies

When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on req.cookie values (which are easy to spoof). Note that signing a cookie does not make it “hidden” or encrypted; but simply prevents tampering (because the secret used to sign is private).

For more information, issues, or concerns, see cookie-parser.

req.stale

req.subdomains

An array of subdomains in the domain name of the request.

req.xhr

A Boolean property that is true if the request’s X-Requested-With header field is “XMLHttpRequest”, indicating that the request was issued by a client library such as jQuery.

Methods

req.accepts(types)

Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns false (in which case, the application should respond with 406 «Not Acceptable» ).

The type value may be a single MIME type string (such as “application/json”), an extension name such as “json”, a comma-delimited list, or an array. For a list or array, the method returns the best match (if any).

For more information, or if you have issues or concerns, see accepts.

For more information, or if you have issues or concerns, see accepts.

For more information, or if you have issues or concerns, see accepts.

For more information, or if you have issues or concerns, see accepts.

req.get(field)

Returns the specified HTTP request header field (case-insensitive match). The Referrer and Referer fields are interchangeable.

req.is(type)

For more information, or if you have issues or concerns, see type-is.

req.range(size[, options])

Range header parser.

The size parameter is the maximum size of the resource.

The options parameter is an object that can have the following properties.

An array of ranges will be returned or negative numbers indicating an error parsing.

Response

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

In this documentation and by convention, the object is always referred to as res (and the HTTP request is req ) but its actual name is determined by the parameters to the callback function in which you’re working.

But you could just as well have:

The res object is an enhanced version of Node’s own response object and supports all built-in fields and methods.

Properties

res.app

This property holds a reference to the instance of the Express application that is using the middleware.

res.app is identical to the req.app property in the request object.

res.headersSent

Boolean property that indicates if the app sent HTTP headers for the response.

res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

Methods

res.append(field [, value])

res.append() is supported by Express v4.11.0+

Note: calling res.set() after res.append() will reset the previously-set header value.

res.attachment([filename])

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

The options parameter is an object that can have the following properties.

All res.cookie() does is set the HTTP Set-Cookie header with the options provided. Any option not specified defaults to the value stated in RFC 6265.

The encode option allows you to choose the function used for cookie value encoding. Does not support asynchronous functions.

Example use case: You need to set a domain-wide cookie for another site in your organization. This other site (not under your administrative control) does not use URI-encoded cookie values.

The maxAge option is a convenience option for setting “expires” relative to the current time in milliseconds. The following is equivalent to the second example above.

You can pass an object as the value parameter; it is then serialized as JSON and parsed by bodyParser() middleware.

Later you may access this value through the req.signedCookies object.

res.clearCookie(name [, options])

res.download(path [, filename] [, options] [, fn])

The optional options argument is supported by Express v4.16.0 onwards.

Transfers the file at path as an “attachment”. Typically, browsers will prompt the user for download. By default, the Content-Disposition header “filename=” parameter is path (this typically appears in the browser dialog). Override this default with the filename parameter.

The optional options argument passes through to the underlying res.sendFile() call, and takes the exact same parameters.

res.end([data] [, encoding])

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

Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().

res.format(object)

Performs content-negotiation on the Accept HTTP header on the request object, when present. It uses req.accepts() to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 “Not Acceptable”, or invokes the default callback.

The following example would respond with < "message": "hey" >when the Accept header field is set to “application/json” or “*/json” (however if it is “*/*”, then the response will be “hey”).

In addition to canonicalized MIME types, you may also use extension names mapped to these types for a slightly less verbose implementation:

res.get(field)

res.json([body])

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

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

res.jsonp([body])

The following are some examples of JSONP responses using the same code:

res.links(links)

Joins the links provided as properties of the parameter to populate the response’s Link HTTP header field.

For example, the following call:

Yields the following results:

res.location(path)

Sets the response Location HTTP header to the specified path parameter.

A path value of “back” has a special meaning, it refers to the URL specified in the Referer header of the request. If the Referer header was not specified, it refers to “/”.

After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the Location header, without any validation.

Browsers take the responsibility of deriving the intended URL from the current URL or the referring URL, and the URL specified in the Location header; and redirect the user accordingly.

res.redirect([status,] path)

Redirects can be a fully-qualified URL for redirecting to a different site:

If you found the above behavior confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.

A back redirection redirects the request back to the referer, defaulting to / when the referer is missing.

res.render(view [, locals] [, callback])

Renders a view and sends the rendered HTML string to the client. Optional parameters:

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 relative to the views setting. If the path does not contain a file extension, then the view engine setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via require() ) and render it using the loaded module’s __express function.

NOTE: The view argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user.

res.send([body])

Sends the HTTP response.

This method performs many useful tasks for simple non-streaming responses: For example, it automatically assigns the Content-Length HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.

When the parameter is a Buffer object, the method sets the Content-Type response header field to “application/octet-stream”, unless previously defined as shown below:

res.sendFile(path [, options] [, fn])

res.sendFile() is supported by Express v4.8.0 onwards.

This API provides access to data on the running file system. Ensure that either (a) the way in which the path argument was constructed into an absolute path is secure if it contains user input or (b) set the root option to the absolute path of a directory to contain access within.

The following table provides details on the options parameter.

UsageExample
Single Middleware
PropertyDescriptionDefaultAvailability
maxAgeSets the max-age property of the Cache-Control header in milliseconds or a string in ms format0
rootRoot directory for relative filenames.
lastModifiedSets the Last-Modified header to the last modified date of the file on the OS. Set false to disable it.Enabled4.9.0+
headersObject containing HTTP headers to serve with the file.
dotfilesOption for serving dotfiles. Possible values are “allow”, “deny”, “ignore”.“ignore”
acceptRangesEnable or disable accepting ranged requests.true4.14+
cacheControlEnable or disable setting Cache-Control response header.true4.14+
immutableEnable or disable the immutable directive in the Cache-Control response header. If enabled, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.false4.16+

The method invokes the callback function fn(err) when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.

Here is an example of using res.sendFile with all its arguments.

The following example illustrates using res.sendFile to provide fine-grained support for serving files:

For more information, or if you have issues or concerns, see send.

res.sendStatus(statusCode)

Sets the response HTTP status code to statusCode and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number.

Some versions of Node.js will throw when res.statusCode is set to an invalid HTTP status code (outside of the range 100 to 599 ). Consult the HTTP server documentation for the Node.js version being used.

res.set(field [, value])

res.status(code)

Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.

res.type(type)

res.vary(field)

Adds the field to the Vary response header, if it is not there already.

Router

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.

You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.

Methods

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

This method is extremely useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you placed the following route at the top of all other route definitions, it would require that all routes from that point on would require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end points; loadUser can perform a task, then call next() to continue matching subsequent routes.

Another example of this is white-listed “global” functionality. Here the example is much like before, but it only restricts paths prefixed with “/api”:

You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched.

The following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are not considered when performing these matches, for example “GET /” would match the following route, as would “GET /?name=tobi”.

You can also use regular expressions—useful if you have very specific constraints, for example the following would match “GET /commits/71dbb9c” as well as “GET /commits/71dbb9c..4c084f9”.

You can use next primitive to implement a flow control between different middleware functions, based on a specific program state. Invoking next with the string ‘router’ will cause all the remaining route callbacks on that router to be bypassed.

The following example illustrates next(‘router’) usage.

router.param(name, callback)

Adds callback triggers to route parameters, where name is the name of the parameter and callback is the callback function. Although name is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below).

The parameters of the callback function are:

For example, when :user is present in a route path, you may map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on router will be triggered only by route parameters defined on router routes.

A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.

The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.

In this example, the router.param(name, callback) signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.

router.route(path)

Returns an instance of a single route which you can then use to handle HTTP verbs with optional middleware. Use router.route() to avoid duplicate route naming and thus typing errors.

Building on the router.param() example above, the following code shows how to use router.route() to specify various HTTP method handlers.

This approach re-uses the single /users/:user_id path and adds handlers for various HTTP methods.

This method is similar to app.use(). A simple example and use case is described below. See app.use() for more information.

Middleware is like a plumbing pipe: requests start at the first middleware function defined and work their way “down” the middleware stack processing for each path they match.

The “mount” path is stripped and is not visible to the middleware function. The main effect of this feature is that a mounted middleware function may operate without code changes regardless of its “prefix” pathname.

The order in which you define middleware with router.use() is very important. They are invoked sequentially, thus the order defines middleware precedence. For example, usually a logger is the very first middleware you would use, so that every request gets logged.

Another example is serving files from multiple directories, giving precedence to “./public” over the others:

The router.use() method also supports named parameters so that your mount points for other routers can benefit from preloading using named parameters.

NOTE: Although these middleware functions are added via a particular router, when they run is defined by the path they are attached to (not the router). Therefore, middleware added via one router may run for other routers if its routes match. For example, this code shows two different routers mounted on the same path:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *