Request API

Table of Contents

Request

Extends http.IncomingMessage

Wraps all of the node http.IncomingMessage 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

Examples

You may pass the subtype such as html which is then converted internally to text/html using the mime lookup table:

// 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 is accepteed

acceptsEncoding

Checks if the request accepts the encoding type(s) specified.

Parameters

Returns Boolean is accepted encoding

contentLength

Returns the value of the content-length header.

Returns Number

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 content type

date

Returns a Date object representing when the request was setup. Like time(), but returns a Date object.

Returns Date date when request began being processed

href

Returns the full requested URL.

Examples

// 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

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

Returns String id

getPath

Returns the cleaned up requested URL.

Examples

// 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

getQuery

Returns the raw query string. Returns empty string if no query string is found.

Examples

// 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:

// incoming request is /foo?a=1
server.use(restify.plugins.queryParser());
req.query;
// => { a: 1 }

Returns String query

time

The number of ms since epoch of when this request began being processed. Like date(), but returns a number.

Returns Number 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

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 the key of the header
  • defaultValue String? default value if header isn’t found on the req

Examples

req.header('Host');
req.header('HOST');
req.header('Accept', '*\/*');

Returns String 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 the name of the header
  • value String default value if header isn’t found on the req

Returns String 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 a content-type header value

Examples

// 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 is content-type header

isChunked

Check if the incoming request is chunked.

Returns Boolean is chunked

isKeepAlive

Check if the incoming request is kept alive.

Returns Boolean is keep alive

isSecure

Check if the incoming request is encrypted.

Returns Boolean is secure

isUpgradeRequest

Check if the incoming request has been upgraded.

Returns Boolean is upgraded

isUpload

Check if the incoming request is an upload verb.

Returns Boolean is upload

toString

toString serialization

Returns String serialized request

userAgent

Returns the user-agent header.

Returns String 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 The name of the handler.

Examples

You must explicitly invoke endHandlerTimer() after invoking this function. Otherwise timing information will be inaccurate.

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 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 The name of the handler.

Returns undefined 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 connection state ("close")

getRoute

Returns the route object to which the current request was matched to.

Examples

Route info object structure:

{
 path: '/ping/:name',
 method: 'GET',
 versions: [],
 name: 'getpingname'
}

Returns Object route

Events

In additional to emitting all the events from node’s 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:

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:

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:

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:

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 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:

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:

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 plugin, the child logger will be available on req.log:

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.


Improve this page