title | permalink |
---|---|
Server API |
/docs/server-api/ |
A restify server object is the main interface through which you will register routes and handlers for incoming requests.
Parameters
options
Object an options objectoptions.name
String Name of the server. (optional, default"restify"
)options.router
Router Router (optional, defaultnewRouter(opts)
)options.log
Object bunyan instance. (optional, defaultbunyan.createLogger(options.name||"restify")
)options.version
(String | Array)? Default version(s) to use in all routes.options.acceptable
Array? String)|List of content-types this server can respond with.options.url
String? Once listen() is called, this will be filled in with where the server is running.options.certificate
(String | Buffer)? If you want to create an HTTPS server, pass in a PEM-encoded certificate and key.options.key
(String | Buffer)? If you want to create an HTTPS server, pass in a PEM-encoded certificate and key.options.formatters
Object? Custom response formatters forres.send()
.options.handleUncaughtExceptions
Boolean When true restify will use a domain to catch and respond to any uncaught exceptions that occur in it's handler stack. bunyan instance. response header, default isrestify
. Pass empty string to unset the header. (optional, defaultfalse
)options.spdy
Object? Any options accepted by node-spdy.options.handleUpgrades
Boolean Hook theupgrade
event from the node HTTP server, pushingConnection: Upgrade
requests through the regular request handling chain. (optional, defaultfalse
)options.httpsServerOptions
Object? Any options accepted by node-https Server. If provided the following restify server options will be ignored: spdy, ca, certificate, key, passphrase, rejectUnauthorized, requestCert and ciphers; however these can all be specified on httpsServerOptions.options.strictRouting
Boolean If set, Restify will treat "/foo" and "/foo/" as different paths. (optional, defaultfalse
)
Examples
var restify = require('restify');
var server = restify.createServer();
srv.listen(8080, function () {
console.log('ready on %s', srv.url);
});
Returns Server server
Creates a new Server.
Parameters
options
Object an options objectoptions.name
String Name of the server.options.router
Router Routeroptions.log
Object bunyan instance.options.version
(String | Array)? Default version(s) to use in all routes.options.acceptable
Array<String>? List of content-types this server can respond with.options.url
String? Once listen() is called, this will be filled in with where the server is running.options.certificate
(String | Buffer)? If you want to create an HTTPS server, pass in a PEM-encoded certificate and key.options.key
(String | Buffer)? If you want to create an HTTPS server, pass in a PEM-encoded certificate and key.options.formatters
Object? Custom response formatters forres.send()
.options.handleUncaughtExceptions
Boolean When true restify will use a domain to catch and respond to any uncaught exceptions that occur in it's handler stack. bunyan instance. response header, default isrestify
. Pass empty string to unset the header. (optional, defaultfalse
)options.spdy
Object? Any options accepted by node-spdy.options.http2
Object? Any options accepted by http2.createSecureServer.options.handleUpgrades
Boolean Hook theupgrade
event from the node HTTP server, pushingConnection: Upgrade
requests through the regular request handling chain. (optional, defaultfalse
)options.httpsServerOptions
Object? Any options accepted by node-https Server. If provided the following restify server options will be ignored: spdy, ca, certificate, key, passphrase, rejectUnauthorized, requestCert and ciphers; however these can all be specified on httpsServerOptions.options.strictRouting
Boolean If set, Restify will treat "/foo" and "/foo/" as different paths. (optional, defaultfalse
)
Examples
var restify = require('restify');
var server = restify.createServer();
srv.listen(8080, function () {
console.log('ready on %s', srv.url);
});
Gets the server up and listening. Wraps node's listen().
Parameters
Examples
You can call like:
server.listen(80)
server.listen(80, '127.0.0.1')
server.listen('/tmp/server.sock')
- Throws TypeError
Returns undefined no return value
Shuts down this server, and invokes callback (optionally) when done. Wraps node's close().
Parameters
callback
Function? callback to invoke when done
Returns undefined no return value
Mounts a chain on the given path against this HTTP verb
Parameters
opts
Server~methodOpts if string, the URL to handle. if options, the URL to handle, at minimum.
Examples
server.get('/', function (req, res, next) {
res.send({ hello: 'world' });
next();
});
Returns Route the newly created route.
Mounts a chain on the given path against this HTTP verb
Parameters
opts
Server~methodOpts if string, the URL to handle. if options, the URL to handle, at minimum.
Returns Route the newly created route.
Mounts a chain on the given path against this HTTP verb
Parameters
post
Server~methodOpts if string, the URL to handle. if options, the URL to handle, at minimum.
Returns Route the newly created route.
Mounts a chain on the given path against this HTTP verb
Parameters
put
Server~methodOpts if string, the URL to handle. if options, the URL to handle, at minimum.
Returns Route the newly created route.
Mounts a chain on the given path against this HTTP verb
Parameters
patch
Server~methodOpts if string, the URL to handle. if options, the URL to handle, at minimum.
Returns Route the newly created route.
Mounts a chain on the given path against this HTTP verb
Parameters
opts
Server~methodOpts if string, the URL to handle. if options, the URL to handle, at minimum.
Returns Route the newly created route.
Mounts a chain on the given path against this HTTP verb
Parameters
opts
Server~methodOpts if string, the URL to handle. if options, the URL to handle, at minimum.
Returns Route the newly created route.
Gives you hooks to run before any routes are located. This gives you a chance to intercept the request and change headers, etc., that routing depends on. Note that req.params will not be set yet.
Parameters
handler
...(Function | Array) Allows you to add handlers that run for all routes. before routing occurs. This gives you a hook to change request headers and the like if you need to. Note thatreq.params
will be undefined, as that's filled in after routing. Takes a function, or an array of functions. variable number of nested arrays of handler functions
Examples
server.pre(function(req, res, next) {
req.headers.accept = 'application/json';
return next();
});
For example, pre()
can be used to deduplicate slashes in
URLs
server.pre(restify.pre.dedupeSlashes());
Returns Object returns self
Allows you to add in handlers that run for all routes. Note that handlers
added
via use()
will run only after the router has found a matching route. If no
match is found, these handlers will never run. Takes a function, or an array
of functions.
You can pass in any combination of functions or array of functions.
Parameters
handler
...(Function | Array) A variable number of handler functions- and/or a variable number of nested arrays of handler functions
Returns Object returns self
Minimal port of the functionality offered by Express.js Route Param Pre-conditions
This basically piggy-backs on the server.use
method. It attaches a
new middleware function that only fires if the specified parameter exists
in req.params
Exposes an API: server.param("user", function (req, res, next) { // load the user's information here, always making sure to call next() });
Parameters
Returns Object returns self
Piggy-backs on the server.use
method. It attaches a new middleware
function that only fires if the specified version matches the request.
Note that if the client does not request a specific version, the middleware function always fires. If you don't want this set a default version with a pre handler on requests where the client omits one.
Exposes an API: server.versionedUse("version", function (req, res, next, ver) { // do stuff that only applies to routes of this API version });
Parameters
versions
(String | Array) the version(s) the URL to respond tofn
Function the middleware function to execute, the fourth parameter will be the selected version
Returns undefined no return value
Removes a route from the server. You pass in the route 'blob' you got from a mount call.
Parameters
Returns Boolean true if route was removed, false if not.
Returns the server address. Wraps node's address().
Examples
server.address()
Output:
{ address: '::', family: 'IPv6', port: 8080 }
Returns Object Address of server
Returns the number of inflight requests currently being handled by the server
Returns number number of inflight requests
Return debug information about the server.
Examples
server.getDebugInfo()
Output:
{
routes: [
{
name: 'get',
method: 'get',
input: '/',
compiledRegex: /^[\/]*$/,
compiledUrlParams: null,
versions: null,
handlers: [Array]
}
],
server: {
formatters: {
'application/javascript': [Function: formatJSONP],
'application/json': [Function: formatJSON],
'text/plain': [Function: formatText],
'application/octet-stream': [Function: formatBinary]
},
address: '::',
port: 8080,
inflightRequests: 0,
pre: [],
use: [ 'parseQueryString', '_jsonp' ],
after: []
}
}
Returns Object debug info
toString() the server for easy reading/output.
Examples
server.toString()
Output:
Accepts: application/json, text/plain, application/octet-stream,
application/javascript
Name: restify
Pre: []
Router: RestifyRouter:
DELETE: []
GET: [get]
HEAD: []
OPTIONS: []
PATCH: []
POST: []
PUT: []
Routes:
get: [parseQueryString, _jsonp, function]
Secure: false
Url: http://[::]:8080
Version:
Returns String stringified server
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.
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 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:
- The handler chain for a route has been fully completed
- 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 objectres
- the response objectroute
- the route object that serviced the requesterror
- the error passed tonext()
, if applicable
Note that when the server automatically responds with a NotFound/MethodNotAllowed/VersionNotAllowed, this event will still be fired.
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 objectres
- the response object
Note that when the server automatically responds with a NotFound/MethodNotAllowed/VersionNotAllowed, this event will still be fired.
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 objectres
- the response objectroute
- 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
.
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 objectres
- the response objectroute
- the route object that serviced the requesterror
- the error passed tonext()
, if applicable
Emitted when the server closes.
Restify handles errors as first class citizens. When an error object is passed
to the next()
function, an event is emitted on the server object, and the
error object will be serialized and sent to the client. An error object is any
object that passes an instanceof Error
check.
Before the error object is sent to the client, the server will fire an event
using the name of the error, without the Error
part of the name. For example,
given an InternalServerError
, the server will emit an InternalServer
event.
This creates opportunities to do logging, metrics, or payload mutation based on
the type of error. For example:
var errs = require('restify-errors');
server.get('/', function(req, res, next) {
return next(new errs.InternalServerError('boom!'));
});
server.on('InternalServer', function(req, res, err, callback) {
// before the response is sent, this listener will be invoked, allowing
// opportunities to do metrics capturing or logging.
myMetrics.capture(err);
// invoke the callback to complete your work, and the server will send out
// a response.
return callback();
});
Inside the error event listener, it is also possible to change the serialization
method of the error if desired. To do so, simply implement a custom
toString()
or toJSON()
. Depending on the content-type and formatter being
used for the response, one of the two serializers will be used. For example,
given the folllwing example:
server.on('restifyError', function(req, res, err, callback) {
err.toJSON = function customToJSON() {
return {
name: err.name,
message: err.message
};
};
err.toString = function customToString() {
return 'i just want a string';
};
return callback();
});
A request with an accept: application/json
will trigger the toJSON()
serializer, while a request with accept: text/plain
will trigger the
toString()
serializer.
Note that the function signature for the error listener is identical for all emitted error events. The signature is as follows:
function(req, res, err, callback) { }
req
- the request objectres
- the response objecterr
- the error objectcallback
- a callback function to invoke
When using this feature in conjunction with restify-errors, restify will emit events for all of the basic http errors:
400
-BadRequestError
401
-UnauthorizedError
402
-PaymentRequiredError
403
-ForbiddenError
404
-NotFoundError
405
-MethodNotAllowedError
406
-NotAcceptableError
407
-ProxyAuthenticationRequiredError
408
-RequestTimeoutError
409
-ConflictError
410
-GoneError
411
-LengthRequiredError
412
-PreconditionFailedError
413
-RequestEntityTooLargeError
414
-RequesturiTooLargeError
415
-UnsupportedMediaTypeError
416
-RangeNotSatisfiableError
(node >= 4)416
-RequestedRangeNotSatisfiableError
(node 0.x)417
-ExpectationFailedError
418
-ImATeapotError
422
-UnprocessableEntityError
423
-LockedError
424
-FailedDependencyError
425
-UnorderedCollectionError
426
-UpgradeRequiredError
428
-PreconditionRequiredError
429
-TooManyRequestsError
431
-RequestHeaderFieldsTooLargeError
500
-InternalServerError
501
-NotImplementedError
502
-BadGatewayError
503
-ServiceUnavailableError
504
-GatewayTimeoutError
505
-HttpVersionNotSupportedError
506
-VariantAlsoNegotiatesError
507
-InsufficientStorageError
509
-BandwidthLimitExceededError
510
-NotExtendedError
511
-NetworkAuthenticationRequiredError
Restify will also emit the following events:
When a client request is sent for a URL that does not exist, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 404 handler.
When a client request is sent for a URL that exists, but not for the requested HTTP verb, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 405 handler.
When a client request is sent for a route that exists, but does not match the version(s) on those routes, restify will emit this event. Note that restify checks for listeners on this event, and if there are none, responds with a default 400 handler.
When a client request is sent for a route that exist, but has a content-type
mismatch, restify will emit this event. Note that restify checks for listeners
on this event, and if there are none, responds with a default 415 handler.
Server method opts
Type: (String | Regexp | Object)
Properties
name
String a name for the routepath
(String | Regexp) a string or regex matching the routeversion
(String | Array<String>) versions supported by this route
Examples
// a static route
server.get('/foo', function(req, res, next) {});
// a parameterized route
server.get('/foo/:bar', function(req, res, next) {});
// a regular expression
server.get(/^\/([a-zA-Z0-9_\.~-]+)\/(.*)/, function(req, res, next) {});
// an options object
server.get({
path: '/foo',
version: ['1.0.0', '2.0.0']
}, function(req, res, next) {});