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

date

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

Returns Date date

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

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
  • aborted - when the socket was closed unexpectedly

Returns String connection state ("closed", "aborted")

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

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