Loc Nguyen
Loc Nguyen

Reputation: 9562

Why isn't Hapi matching this path when I set the HTTP method to *

My goal is to create a route to proxy requests to a specific path to a remote API. I'm having trouble making this route match GET requests. POST requests are matched and the call is passed through. For example, a POST request from the browser to /api/document proxies to the destination successfully. Hapi responds to GET /api/document with a 404, though. I can create two identical routes with different values for the method key but that doesn't seem DRY.

    server.route({
    path: '/api/{path*}',
    method: '*',
    config: {
        handler: {
            proxy: {
                passThrough: true,
                mapUri: function (request, callback) {
                    var baseUri = 'https://remote/services/v1';
                    var resourceUri = request.path.replace('/api', '');
                    var destinationUri = baseUri + resourceUri;

                    server.log('Proxying to: ' + destinationUri);
                    callback(null, destinationUri);   
                }
            }
        }
    }
});

    server.route({
        method: 'GET',
        path: '/{path*}',
        handler: {
            file: '../build/index.html'
        }
    });

Upvotes: 2

Views: 1905

Answers (1)

Phi D
Phi D

Reputation: 36

According to the docs, when you use the '' wildcard for the method in your route it will only match when an exact match isn't found. Your 'catchall' route's method matches the route and the method is more specific so it appears to be going through the /{path} route instead.

method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually.

You can probably fix this by either using a wildcard for your catch all or passing an array for the proxy route instead of using the wildcard.

Upvotes: 2

Related Questions