--- title: Request API permalink: /docs/request-api/ --- ### Table of Contents - [Request][1] - [accepts][2] - [acceptsEncoding][3] - [contentLength][4] - [getContentType][5] - [date][6] - [href][7] - [id][8] - [getPath][9] - [getQuery][10] - [time][11] - [version][12] - [header][13] - [trailer][14] - [is][15] - [isChunked][16] - [isKeepAlive][17] - [isSecure][18] - [isUpgradeRequest][19] - [isUpload][20] - [toString][21] - [userAgent][22] - [startHandlerTimer][23] - [endHandlerTimer][24] - [connectionState][25] - [getRoute][26] - [Events][27] - [Log][28] ## Request **Extends http.IncomingMessage** Wraps all of the node [http.IncomingMessage][29] APIs, events and properties, plus the following. ### accepts Check if the Accept header is present, and includes the given type. When the Accept header is not present true is returned. Otherwise the given type is matched by an exact match, and then subtypes. **Parameters** - `types` **([String][30] \| [Array][31]<[String][30]>)** an array of accept type headers **Examples** You may pass the subtype such as html which is then converted internally to text/html using the mime lookup table: ```javascript // Accept: text/html req.accepts('html'); // => true // Accept: text/*; application/json req.accepts('html'); req.accepts('text/html'); req.accepts('text/plain'); req.accepts('application/json'); // => true req.accepts('image/png'); req.accepts('png'); // => false ``` Returns **[Boolean][32]** is accepteed ### acceptsEncoding Checks if the request accepts the encoding type(s) specified. **Parameters** - `types` **([String][30] \| [Array][31]<[String][30]>)** an array of accept type headers Returns **[Boolean][32]** is accepted encoding ### contentLength Returns the value of the content-length header. Returns **[Number][33]** ### getContentType Returns the value of the content-type header. If a content-type is not set, this will return a default value of `application/octet-stream` Returns **[String][30]** content type ### date Returns a Date object representing when the request was setup. Like `time()`, but returns a Date object. Returns **[Date][34]** date when request began being processed ### href Returns the full requested URL. **Examples** ```javascript // incoming request is http://localhost:3000/foo/bar?a=1 server.get('/:x/bar', function(req, res, next) { console.warn(req.href()); // => /foo/bar/?a=1 }); ``` Returns **[String][30]** ### id Returns the request id. If a `reqId` value is passed in, this will become the request’s new id. The request id is immutable, and can only be set once. Attempting to set the request id more than once will cause restify to throw. **Parameters** - `reqId` **[String][30]** request id Returns **[String][30]** id ### getPath Returns the cleaned up requested URL. **Examples** ```javascript // incoming request is http://localhost:3000/foo/bar?a=1 server.get('/:x/bar', function(req, res, next) { console.warn(req.path()); // => /foo/bar }); ``` Returns **[String][30]** ### getQuery Returns the raw query string. Returns empty string if no query string is found. **Examples** ```javascript // incoming request is /foo?a=1 req.getQuery(); // => 'a=1' ``` If the queryParser plugin is used, the parsed query string is available under the req.query: ```javascript // incoming request is /foo?a=1 server.use(restify.plugins.queryParser()); req.query; // => { a: 1 } ``` Returns **[String][30]** query ### time The number of ms since epoch of when this request began being processed. Like date(), but returns a number. Returns **[Number][33]** time when request began being processed in epoch: ellapsed milliseconds since January 1, 1970, 00:00:00 UTC ### version Returns the accept-version header. Returns **[String][30]** ### header Get the case-insensitive request header key, and optionally provide a default value (express-compliant). Returns any header off the request. also, 'correct' any correctly spelled 'referrer' header to the actual spelling used. **Parameters** - `key` **[String][30]** the key of the header - `defaultValue` **[String][30]?** default value if header isn't found on the req **Examples** ```javascript req.header('Host'); req.header('HOST'); req.header('Accept', '*\/*'); ``` Returns **[String][30]** header value ### trailer Returns any trailer header off the request. Also, 'correct' any correctly spelled 'referrer' header to the actual spelling used. **Parameters** - `name` **[String][30]** the name of the header - `value` **[String][30]** default value if header isn't found on the req Returns **[String][30]** trailer value ### is Check if the incoming request contains the `Content-Type` header field, and if it contains the given mime type. **Parameters** - `type` **[String][30]** a content-type header value **Examples** ```javascript // With Content-Type: text/html; charset=utf-8 req.is('html'); req.is('text/html'); // => true // When Content-Type is application/json req.is('json'); req.is('application/json'); // => true req.is('html'); // => false ``` Returns **[Boolean][32]** is content-type header ### isChunked Check if the incoming request is chunked. Returns **[Boolean][32]** is chunked ### isKeepAlive Check if the incoming request is kept alive. Returns **[Boolean][32]** is keep alive ### isSecure Check if the incoming request is encrypted. Returns **[Boolean][32]** is secure ### isUpgradeRequest Check if the incoming request has been upgraded. Returns **[Boolean][32]** is upgraded ### isUpload Check if the incoming request is an upload verb. Returns **[Boolean][32]** is upload ### toString toString serialization Returns **[String][30]** serialized request ### userAgent Returns the user-agent header. Returns **[String][30]** user agent ### startHandlerTimer Start the timer for a request handler. By default, restify uses calls this automatically for all handlers registered in your handler chain. However, this can be called manually for nested functions inside the handler chain to record timing information. **Parameters** - `handlerName` **[String][30]** The name of the handler. **Examples** You must explicitly invoke endHandlerTimer() after invoking this function. Otherwise timing information will be inaccurate. ```javascript server.get('/', function fooHandler(req, res, next) { vasync.pipeline({ funcs: [ function nestedHandler1(req, res, next) { req.startHandlerTimer('nestedHandler1'); // do something req.endHandlerTimer('nestedHandler1'); return next(); }, function nestedHandler1(req, res, next) { req.startHandlerTimer('nestedHandler2'); // do something req.endHandlerTimer('nestedHandler2'); return next(); }... ]... }, next); }); ``` Returns **[undefined][35]** no return value ### endHandlerTimer End the timer for a request handler. You must invoke this function if you called `startRequestHandler` on a handler. Otherwise the time recorded will be incorrect. **Parameters** - `handlerName` **[String][30]** The name of the handler. Returns **[undefined][35]** no return value ### connectionState Returns the connection state of the request. Current possible values are: - `close` - when the request has been closed by the clien Returns **[String][30]** connection state (`"close"`) ### getRoute Returns the route object to which the current request was matched to. **Examples** Route info object structure: ```javascript { path: '/ping/:name', method: 'GET', versions: [], name: 'getpingname' } ``` Returns **[Object][36]** route ## Events In additional to emitting all the events from node's [http.Server][37], restify servers also emit a number of additional events that make building REST and web applications much easier. ### restifyError This event is emitted following all error events as a generic catch all. It is recommended to use specific error events to handle specific errors, but this event can be useful for metrics or logging. If you use this in conjunction with other error events, the most specific event will be fired first, followed by this one: ```js server.get('/', function(req, res, next) { return next(new InternalServerError('boom')); }); server.on('InternalServer', function(req, res, err, callback) { // this will get fired first, as it's the most relevant listener return callback(); }); server.on('restifyError', function(req, res, err, callback) { // this is fired second. return callback(); }); ``` ### after After each request has been fully serviced, an `after` event is fired. This event can be hooked into to handle audit logs and other metrics. Note that flushing a response does not necessarily correspond with an `after` event. restify considers a request to be fully serviced when either: 1) The handler chain for a route has been fully completed 2) An error was returned to `next()`, and the corresponding error events have been fired for that error type The signature is for the after event is as follows: ```js function(req, res, route, error) { } ``` - `req` - the request object - `res` - the response object - `route` - the route object that serviced the request - `error` - the error passed to `next()`, if applicable Note that when the server automatically responds with a NotFound/MethodNotAllowed/VersionNotAllowed, this event will still be fired. ### pre Before each request has been routed, a `pre` event is fired. This event can be hooked into handle audit logs and other metrics. Since this event fires _before_ routing has occured, it will fire regardless of whether the route is supported or not, e.g. requests that result in a `404`. The signature for the `pre` event is as follows: ```js function(req, res) {} ``` - `req` - the request object - `res` - the response object Note that when the server automatically responds with a NotFound/MethodNotAllowed/VersionNotAllowed, this event will still be fired. ### routed A `routed` event is fired after a request has been routed by the router, but before handlers specific to that route has run. The signature for the `routed` event is as follows: ```js function(req, res, route) {} ``` - `req` - the request object - `res` - the response object - `route` - the route object that serviced the request Note that this event will _not_ fire if a requests comes in that are not routable, i.e. one that would result in a `404`. ### uncaughtException If the restify server was created with `handleUncaughtExceptions: true`, restify will leverage [domains][38] to handle thrown errors in the handler chain. Thrown errors are a result of an explicit `throw` statement, or as a result of programmer errors like a typo or a null ref. These thrown errors are caught by the domain, and will be emitted via this event. For example: ```js server.get('/', function(req, res, next) { res.send(x); // this will cause a ReferenceError return next(); }); server.on('uncaughtException', function(req, res, route, err) { // this event will be fired, with the error object from above: // ReferenceError: x is not defined }); ``` If you listen to this event, you **must** send a response to the client. This behavior is different from the standard error events. If you do not listen to this event, restify's default behavior is to call `res.send()` with the error that was thrown. The signature is for the after event is as follows: ```js function(req, res, route, error) { } ``` - `req` - the request object - `res` - the response object - `route` - the route object that serviced the request - `error` - the error passed to `next()`, if applicable ### close Emitted when the server closes. ## Log If you are using the [RequestLogger][39] plugin, the child logger will be available on `req.log`: ```js function myHandler(req, res, next) { var log = req.log; log.debug({params: req.params}, 'Hello there %s', 'foo'); } ``` The child logger will inject the request's UUID in the `req._id` attribute of each log statement. Since the logger lasts for the life of the request, you can use this to correlate statements for an individual request across any number of separate handlers. [1]: #request [2]: #accepts [3]: #acceptsencoding [4]: #contentlength [5]: #getcontenttype [6]: #date [7]: #href [8]: #id [9]: #getpath [10]: #getquery [11]: #time [12]: #version [13]: #header [14]: #trailer [15]: #is [16]: #ischunked [17]: #iskeepalive [18]: #issecure [19]: #isupgraderequest [20]: #isupload [21]: #tostring [22]: #useragent [23]: #starthandlertimer [24]: #endhandlertimer [25]: #connectionstate [26]: #getroute [27]: #events [28]: #log [29]: https://nodejs.org/api/http.html [30]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String [31]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array [32]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean [33]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number [34]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date [35]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined [36]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [37]: http://nodejs.org/docs/latest/api/http.html#http_class_http_server [38]: https://nodejs.org/api/domain.html [39]: #bundled-plugins