2017-10-21 07:24:48 +02:00
---
title: Request API
permalink: /docs/request-api/
---
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
### Table of Contents
2018-04-20 11:44:05 -07:00
- [Request ](#request )
- [accepts ](#accepts )
- [acceptsEncoding ](#acceptsencoding )
- [contentLength ](#contentlength )
- [getContentType ](#getcontenttype )
- [date ](#date )
- [href ](#href )
- [id ](#id )
- [getPath ](#getpath )
- [getQuery ](#getquery )
- [time ](#time )
- [version ](#version )
- [header ](#header )
- [trailer ](#trailer )
- [is ](#is )
- [isChunked ](#ischunked )
- [isKeepAlive ](#iskeepalive )
- [isSecure ](#issecure )
- [isUpgradeRequest ](#isupgraderequest )
- [isUpload ](#isupload )
- [toString ](#tostring )
- [userAgent ](#useragent )
- [startHandlerTimer ](#starthandlertimer )
- [endHandlerTimer ](#endhandlertimer )
- [connectionState ](#connectionstate )
- [getRoute ](#getroute )
2019-01-18 16:19:16 -08:00
- [Events ](#events )
2018-04-20 11:44:05 -07:00
- [Log ](#log )
2017-10-21 07:24:48 +02:00
## Request
**Extends http.IncomingMessage **
2017-10-24 22:22:30 +02:00
Wraps all of the node
2018-04-20 11:44:05 -07:00
[http.IncomingMessage ](https://nodejs.org/api/http.html )
2017-10-21 07:24:48 +02:00
APIs, events and properties, plus the following.
### accepts
2017-10-24 22:22:30 +02:00
Check if the Accept header is present, and includes the given type.
2017-10-21 07:24:48 +02:00
When the Accept header is not present true is returned.
Otherwise the given type is matched by an exact match, and then subtypes.
**Parameters **
2018-04-20 11:44:05 -07:00
- `types` * * ([String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String ) \| [Array ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array )<[String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )>)** an array of accept type headers
2017-10-21 07:24:48 +02:00
**Examples **
2017-11-02 19:00:16 +01:00
_You may pass the subtype such as html which is then converted internally
to text/html using the mime lookup table:_
2017-10-21 07:24:48 +02:00
``` 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
```
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is accepteed
2017-10-21 07:24:48 +02:00
### acceptsEncoding
Checks if the request accepts the encoding type(s) specified.
**Parameters **
2018-04-20 11:44:05 -07:00
- `types` * * ([String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String ) \| [Array ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array )<[String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )>)** an array of accept type headers
2017-10-21 07:24:48 +02:00
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is accepted encoding
2017-10-21 07:24:48 +02:00
### contentLength
Returns the value of the content-length header.
2018-04-20 11:44:05 -07:00
Returns * * [Number ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number )**
2017-10-21 07:24:48 +02:00
### getContentType
2017-11-02 19:00:16 +01:00
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`
2017-10-21 07:24:48 +02:00
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** content type
2017-10-21 07:24:48 +02:00
### date
2017-10-24 22:22:30 +02:00
Returns a Date object representing when the request was setup.
2017-10-21 07:24:48 +02:00
Like `time()` , but returns a Date object.
2018-04-20 11:44:05 -07:00
Returns * * [Date ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date )** date when request began being processed
2017-10-21 07:24:48 +02:00
### 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
} ) ;
```
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )**
2017-10-21 07:24:48 +02:00
### id
2017-10-24 22:22:30 +02:00
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
2017-10-21 07:24:48 +02:00
once will cause restify to throw.
**Parameters **
2018-04-20 11:44:05 -07:00
- `reqId` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** request id
2017-10-21 07:24:48 +02:00
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** id
2017-10-21 07:24:48 +02:00
### 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
} ) ;
```
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )**
2017-10-21 07:24:48 +02:00
### getQuery
2017-10-24 22:22:30 +02:00
Returns the raw query string. Returns empty string
if no query string is found.
2017-10-21 07:24:48 +02:00
**Examples **
``` javascript
// incoming request is /foo?a=1
req . getQuery ( ) ;
// => 'a=1'
```
2017-10-24 22:22:30 +02:00
_If the queryParser plugin is used, the parsed query string is
2017-10-21 07:24:48 +02:00
available under the req.query:_
``` javascript
// incoming request is /foo?a=1
server . use ( restify . plugins . queryParser ( ) ) ;
req . query ;
// => { a: 1 }
```
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** query
2017-10-21 07:24:48 +02:00
### time
2017-10-24 22:22:30 +02:00
The number of ms since epoch of when this request began being processed.
2017-10-21 07:24:48 +02:00
Like date(), but returns a number.
2018-04-20 11:44:05 -07:00
Returns * * [Number ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number )** time when request began being processed in epoch:
2017-12-18 18:59:17 +01:00
ellapsed milliseconds since
January 1, 1970, 00:00:00 UTC
2017-10-21 07:24:48 +02:00
### version
Returns the accept-version header.
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )**
2017-10-21 07:24:48 +02:00
### header
2017-10-24 22:22:30 +02:00
Get the case-insensitive request header key,
2017-10-21 07:24:48 +02:00
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 **
2018-04-20 11:44:05 -07:00
- `key` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** the key of the header
- `defaultValue` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )?** default value if header isn't
2017-10-21 07:24:48 +02:00
found on the req
**Examples **
``` javascript
req . header ( 'Host' ) ;
req . header ( 'HOST' ) ;
req . header ( 'Accept' , '*\/*' ) ;
```
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** header value
2017-10-21 07:24:48 +02:00
### trailer
2017-10-24 22:22:30 +02:00
Returns any trailer header off the request. Also, 'correct' any
2017-10-21 07:24:48 +02:00
correctly spelled 'referrer' header to the actual spelling used.
**Parameters **
2018-04-20 11:44:05 -07:00
- `name` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** the name of the header
- `value` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** default value if header isn't found on the req
2017-10-21 07:24:48 +02:00
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** trailer value
2017-10-21 07:24:48 +02:00
### is
2017-10-24 22:22:30 +02:00
Check if the incoming request contains the `Content-Type` header field,
2017-10-21 07:24:48 +02:00
and if it contains the given mime type.
**Parameters **
2018-04-20 11:44:05 -07:00
- `type` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** a content-type header value
2017-10-21 07:24:48 +02:00
**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
```
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is content-type header
2017-10-21 07:24:48 +02:00
### isChunked
Check if the incoming request is chunked.
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is chunked
2017-10-21 07:24:48 +02:00
### isKeepAlive
Check if the incoming request is kept alive.
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is keep alive
2017-10-21 07:24:48 +02:00
### isSecure
Check if the incoming request is encrypted.
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is secure
2017-10-21 07:24:48 +02:00
### isUpgradeRequest
Check if the incoming request has been upgraded.
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is upgraded
2017-10-21 07:24:48 +02:00
### isUpload
Check if the incoming request is an upload verb.
2018-04-20 11:44:05 -07:00
Returns * * [Boolean ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean )** is upload
2017-10-21 07:24:48 +02:00
### toString
toString serialization
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** serialized request
2017-10-21 07:24:48 +02:00
### userAgent
Returns the user-agent header.
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** user agent
2017-10-21 07:24:48 +02:00
### startHandlerTimer
2017-10-24 22:22:30 +02:00
Start the timer for a request handler.
By default, restify uses calls this automatically for all handlers
registered in your handler chain.
2017-11-02 19:00:16 +01:00
However, this can be called manually for nested functions inside the
handler chain to record timing information.
2017-10-21 07:24:48 +02:00
**Parameters **
2018-04-20 11:44:05 -07:00
- `handlerName` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** The name of the handler.
2017-10-21 07:24:48 +02:00
**Examples **
_You must explicitly invoke
2017-11-02 19:00:16 +01:00
endHandlerTimer() after invoking this function. Otherwise timing
information will be inaccurate._
2017-10-21 07:24:48 +02:00
``` 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 ) ;
} ) ;
```
2018-04-20 11:44:05 -07:00
Returns * * [undefined ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined )** no return value
2017-10-21 07:24:48 +02:00
### endHandlerTimer
2017-10-24 22:22:30 +02:00
End the timer for a request handler.
You must invoke this function if you called `startRequestHandler` on a
2017-10-21 07:24:48 +02:00
handler. Otherwise the time recorded will be incorrect.
**Parameters **
2018-04-20 11:44:05 -07:00
- `handlerName` * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** The name of the handler.
2017-10-21 07:24:48 +02:00
2018-04-20 11:44:05 -07:00
Returns * * [undefined ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined )** no return value
2017-10-21 07:24:48 +02:00
### connectionState
Returns the connection state of the request. Current possible values are:
- `close` - when the request has been closed by the clien
2018-04-20 11:44:05 -07:00
Returns * * [String ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String )** connection state (`"close"` )
2017-10-21 07:24:48 +02:00
### 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'
}
```
2018-04-20 11:44:05 -07:00
Returns * * [Object ](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object )** route
2017-10-21 07:24:48 +02:00
2019-01-18 16:19:16 -08:00
## Events
In additional to emitting all the events from node's
[http.Server ](http://nodejs.org/docs/latest/api/http.html#http_class_http_server ),
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 ](https://nodejs.org/api/domain.html ) 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.
2017-10-21 07:24:48 +02:00
## Log
2018-04-20 11:44:05 -07:00
If you are using the [RequestLogger ](#bundled-plugins ) plugin, the child logger
2017-10-21 07:24:48 +02:00
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.