The arguments are:. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information.
Defaults to Date. Return value: the route information if found, otherwise null. Defaults to active context set via server. The generateTimeout option is required, and the generateFunc options is not allowed. The server will automatically generate a unique key if the function's arguments are all of types 'string' , 'number' , or 'boolean'.
However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string or null if no key can be generated. Method names can be nested e. When configured with caching enabled, server. Registers a server method function as described in server. Sets the path prefix used to locate static resources files and view templates when relative paths are used where:.
Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files. The path only applies to routes added after it has been set.
Cannot be used with plugin options. If not set to true , an error will be thrown the second time a plugin is registered on the server. Incoming requests are compared to the configured paths based on the server's router configuration.
Can be assigned an array of methods which has the same result as adding the same route with different methods manually. Matching is done against the hostname part of the header only excluding the port. Defaults to all hosts. The options value can be an object or a function that returns an object using the signature function server where server is the server the route is being added to and this is bound to the current realm 's bind option.
The object is passed to each rules processor registered with server. Cannot be used if route. Note that the options object is deeply cloned with the exception of bind which is shallowly copied and cannot contain any values that are unsafe to perform deep copy on.
Parameterized paths are processed by matching the named parameters to the content of the incoming request path at that path segment. A path parameter may only contain letters, numbers and underscores, e. An optional '? In addition to the optional? The router iterates through the routing table on each incoming request and executes the first and only the first matching route. Route matching is done based on the combination of the request path and the HTTP verb e. The query is excluded from the routing logic.
Requests are matched in a deterministic order where the order in which routes are added does not matter. Routes are matched based on the specificity of the route which is evaluated at each segment of the incoming request path. The segments are compared to the routing table one at a time and are matched against the most specific path until a match is found. If no match is found, the next match is tried. Note that mixed parameters are slower to compare as they cannot be hashed and require an array iteration over all the regular expressions representing the various mixed parameter at each routing table node.
If the application needs to override the default Not Found error response, it can add a catch-all route for a specific method or all methods. Only one catch-all route can be defined. Defines a route rules processor for converting route rules object into route configuration where:.
Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin overrides the config generated by the root processor if they overlap.
Similarly, the route's own config overrides the config produced by the rules processors. Starts the server by listening for incoming requests on the configured port unless the connection was configured with autoListen set to false. If a started server is started again, the second call to server. No events will be emitted and no extension points invoked. HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:.
Defaults to null session time-life - cookies are deleted when the browser is closed. The value must be one of:.
The value can be a function with signature async function request where:. Options are:. This does not provide privacy, only a mean to verify that the cookie value was generated by the server.
Redundant when 'iron' encoding is used. Defaults to require 'iron'. State defaults can be modified via the server. Registered cookies are automatically parsed when received.
Parsing rules depends on the route state. If an incoming registered cookie fails parsing, it is not included in request. When state. To capture these errors subscribe to the 'request' event on the 'internal' channel and filter on 'error' and 'state' tags:. Note that this utility uses the server configuration but does not change the server state.
It is provided for manual cookie formatting e. It is provided for manual cookie parsing e. Stops the server's listener by refusing to accept any new connections or requests existing connections will continue until closed or timeout , where:.
Registers a server validation module used to compile raw validation rules into validation schemas for all routes where:. Note: the validator is only used when validation rules are not pre-compiled schemas.
When a validation rules is a function or schema object, the rule is used as-is and the validator is not used. When setting a validator inside a plugin, the validator is only applied to routes set up by the plugin and plugins registered by it.
Application-specific route configuration state. Should not be used by plugins which should use options. The strategy will be set to 'required' mode. An object or array of objects specifying the route access rules.
Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object must include at least one of scope or entity.
The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least one of the scopes defined to access the route. If a scope string begins with a! For example, the scope ['! The required authenticated entity type.
If set, must match the entity value of the request authenticated credentials. Available values:. If set, the incoming request payload is authenticated after it is processed.
Requires a strategy with payload authentication support e. Cannot be set to a value other than 'required' when the scheme sets the authentication options. Default value: the default strategy set via server. An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. A string strategy names. Cannot be used together with strategies. An object passed back to the provided handler via this when called. Caching can be customized using an object with the following options:.
Values are:. The default Cache-Control: no-cache header can be disabled by setting cache to false. An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression.
CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.
To enable, set cors to true , or to an object with the following options:. The greater the value, the longer it will take before the browser checks for changes in policy.
Defaults to one day. Use this to keep the default headers in place. This setting is not available when setting server route defaults using server. Route-level request extension points by setting the option to an object with a key for each of the desired extension points 'onRequest' is not allowed , and the value is the same as the server. The route handler function performs the main business logic of the route and sets the response. The matching property value is passed as options to the registered handler generator.
Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.
An optional unique identifier used to look up the route using server. Cannot be assigned to routes added with an array of methods. If true , the route cannot be accessed through the HTTP listener but only through the server. Used for internal routes that should not be accessible to the outside world. Optional arguments passed to JSON. Supports the following:.
Defaults to no suffix. Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. Cannot be used with stream responses. A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types.
Note that allowing additional mime types not listed above will not enable them to be parsed, and if parse is true , the request will result in an error response. An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. A failAction value which determines how to handle payload parsing errors.
Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. If parse is false , a raw Buffer is returned. Readable interface. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire multipart content loaded into memory.
To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser e. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used e. If the format is unknown, a Bad Request error response is sent. Any known content encoding is decoded. Sets handling of incoming payload that may contain a prototype poisoning security attack.
Use this option only when you are sure that such incoming data cannot pose any risks to your application. Payload reception timeout in milliseconds.
Sets the maximum time allowed for the client to transmit the request payload body before giving up and responding with a Request Timeout error response. Plugin-specific configuration.
The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared across routes, as well as provide a cleaner error handling of prerequisite operations e. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Who owns this outage?
Building intelligent escalation chains for modern SRE. Podcast Who is building clouds for the independent developer?
Featured on Meta. Now live: A fully responsive profile. Reducing the weight of our footer. This is done to prevent echo or XSS attacks.
One way to do this is to use Hoek escapeHtml method. With escaping in place, the above example would look like the following:. These parameters are stored in the object request. Since you named your parameter user, you are able to access the value with the property request. In order to make a parameter optional, put a question mark at the end of the parameter's name. Here is the same route, but updated to make the user parameter optional:.
It is important to be aware that only the last named parameter in a path can be optional. Along with optional path parameters, you can also allow parameters that match multiple segments. In order to do this, you use an asterisk and a number. That's why you did a split on that character to get the two separate parts. The number after the asterisk represents how many path segments should be assigned to the parameter. You can also omit the number entirely, and the parameter will match any number of segments available.
When determining what handler to use for a particular request, hapi searches paths in order from most specific to least specific. Query parameters are common way of sending data to the server. In hapi, you can access query parameters by the request.
Here, you simply access the name query parameter and return it in the handler, which would read Hello ferris! For more complex query structures, you may opt to use the qs module. Consider the following:. If you sent the request localhost?
Leverage the new response toolkit to send a redirect or create your desired response. The following code block shows some response samples and how to use the h response toolkit. In hapi v16, you had access to the reply interface which was a powerful callback method that returned a response object. This response was chainable for further manipulation. The new response toolkit provides most of the functionality that you had access to with the reply interface.
When calling reply in hapi v16 and lower, the return value was the response object. You could customize it by adding headers or updating the status code. The response object was chainable to update the response with a single statement.
In hapi v17, the response toolkit handles the same job and returns a response object when calling h. Return the response when ready. In case you created a response object in hapi v16 and wanted to execute long-running jobs asynchronously, you needed to use the. This was the way to prevent an early response. Both, response. Each request served with hapi follows a predefined path: the request lifecycle.
Depending on whether you need authentication or validation, the framework skips individual lifecycle points. This extension point locates after onPreAuth and before onPostAuth. In onPreAuth , hapi authenticates the request and identifies the user. The authorization is part of onPostAuth , like checking the request scope to verify that the request has access rights.
In onCredentials , you can customize the credentials before the request authorization. You can either use an async function to await the server start or make use of promises. Actually, you can use promises to start your hapi server in v16 already. Besides that, the error callback is available. Well, the server. To stop your hapi server accordingly , close existing connections.
With v17 you need to use an async function or a promise. Same as with server. If you want to run functionality after the server stopped, chain an. Features like validation and handling for failed validation are part of a dedicated route configuration. You need to specify an object with the functionality, like validate. You can also add the handler in the configuration. In hapi v17, this object changes its name from config to options. The config key will still work, but is deprecated.
Check your project for routes that make use of the config object. Routes with validation will use it. Keep your project future proof and replace config with options. Configure failAction in v17 to either ignore , log , error or a lifecycle method with the signature async function request, h, error.
In this situation, hapi allows you to return an error, a takeover response or a continue signal. For web requests from views, you want to render the view again with error details so that the user can react on the new situation. To respond with a view from failAction , use the.
Keep an eye on your route handlers with validation. In case you want to respond a web view, use the. The response toolkit h replaces the reply interface which allows you to respond requests accordingly. The source —where the validation error occurs— moves into the error object.
Check the validations at your routes and update the failAction to support the new response toolkit h and the updated signature where the source object moves into the error object.
0コメント