[Hapi.js] Route parameters

Routing is a fundamental aspect of any framework. In this lesson, you‘ll learn how to use path parameters in hapi‘s router. We‘ll also touch on how the router uses specificity to order routes internally.

Router Param:

http://localhost:8000/ztw

// Will match any string after /    

    server.route( {
        method: ‘GET‘,
        path: ‘/{name}‘,
        handler: function ( request, reply ) {
            reply( "hello " + request.params.name + "!" ); // hello ztw
        }
    } );

http://localhost:8000/user/ztw:

    server.route( {
        method: ‘GET‘,
        path: ‘/user/{name}‘,
        handler: function ( request, reply ) {
            reply( "hello " + request.params.name + "!" );
        }
    } );

Optional parameters

    server.route( {
        method: ‘GET‘,
        path: ‘/user/{name?}‘,
        handler: function ( request, reply ) {
            var name = request.params.name ? request.params.name : "AAAA";
            reply( "hello " + name + "!" );
        }
    } );

http://localhost:8000/user/ztw:

// hello ztw!

http://localhost:8000/user/:

// hello AAAA!
    server.route( {
        method: ‘GET‘,
        path: ‘/user/{name}/address‘,
        handler: function ( request, reply ) {

            reply( request.params.name + "‘s address: Finland" );
        }
    } );

http://localhost:8000/user/ztw/address:

// ztw‘s address: Finland

Multi-segment parameters

    server.route({
        method: ‘GET‘,
        path: ‘/hello/{user*2}‘,
        handler: function (request, reply) {
            const userParts = request.params.user.split(‘/‘);
            reply(‘Hello ‘ + encodeURIComponent(userParts[0]) + ‘ ‘ + encodeURIComponent(userParts[1]) + ‘!‘);
        }
    });

http://localhost:8000/hello/ztw/twz:

// Hello ztw twz!

If pass the third params, it will report error.

    server.route({
        method: ‘GET‘,
        path: ‘/files/{file*}‘,
        handler: function(request, reply){
            reply(request.params);
        }
    })

http://localhost:8000/files/sky/night/aurora/100.jpg:

// {"file":"sky/night/aurora/100.jpg"}
    server.route({
        method: ‘GET‘,
        path: ‘/files/{file}.jpg‘,
        handler: function(request, reply){
            reply(request.params);
        }
    })

http://localhost:8000/files/100.jpg:

// {"file":"100"}

The last thing I‘d like to cover is path specificity. Hapi‘s router evaluates routes in order from most specific to least specific, which means that the order routes are created does not affect the order they are evaluated.

    server.route({
        method: ‘GET‘,
        path: ‘/files/{file*}‘,
        handler: function(request, reply){
            reply(request.params);
        }
    })

    server.route({
        method: ‘GET‘,
        path: ‘/files/{file}.jpg‘,
        handler: function(request, reply){
            reply(request.params);
        }
    })

If I give the url:

http://localhost:8000/files/100.jpg, it will match the second router instead of the first router.

But if I gave http://localhost:8000/files/b/100.jpg

// {"file":"b/100.jpg"}

It will match the first router.

时间: 2024-08-11 05:33:07

[Hapi.js] Route parameters的相关文章

[Hapi.js] Logging with good and good-console

hapi doesn't ship with logging support baked in. Luckily, hapi's rich plugin ecosystem includes everything needed to configure logging for your application. This post will introduce good, a process monitor for hapi, and good-console, a reporter for g

[Hapi.js] Request Validation with Joi

hapi supports request validation out of the box using the joi module. Request path parameters, payloads, and querystring parameters can be validated with joi's simple, 'use strict' const Hapi = require('hapi') const Joi = require('joi') const server

[Hapi.js] View engines

View engines, or template engines, allow you to maintain a clean separation between your presentation layer and the rest of your application. This post will demonstrate how to use the vision plugin with hapi to enable template support. index.js serve

[Hapi.js] Serving static files

hapi does not support serving static files out of the box. Instead it relies on a module called Inert. This lesson will cover serving static files using Inert's custom handlers. 'use strict' var Hapi = require( 'hapi' ); var Boom = require('boom'); v

[Hapi.js] Managing State with Cookies

hapi has built-in support for parsing cookies from a request headers, and writing cookies to a response, making state management easy and straight-forward. It even has built in support for cookie encryption and auto detects when a cookie contains JSO

[Hapi.js] Friendly error pages with extension events

hapi automatically responds with JSON for any error passed to a route's reply()method. But what if your application needs errors rendered in HTML? This lesson shows how to implement friendly HTML error messages using hapi extension events. const Hapi

[Hapi.js] Extending the request with lifecycle events

Instead of using middlware, hapi provides a number of points during the lifecycle of a request that you can hook-in to provide additional functionality, called "extension events". This lesson will give you an introduction to using extension even

[Hapi.js] Replying to Requests

hapi's reply interface is one of it's most powerful features. It's smart enough to detect and serialize objects, buffers, promises and even streams. This post will demonstrate first hand how to use the reply method to send your data to the client, no

[Hapi.js] Using the response object

When you use reply method: let resp = reply('hello world') It actually return an response object. By using response object, you can modiy the response's status code, header, cookie, type and so on... server.route({ method: 'GET', path: '/', handler: