'Hapjs Route Prerequisite is executed and route is always returning 404

I am building a web application using Hapijs. I am using route prerequisites to do something before the route handler is executed.

This is my route

server.route([
    {
        method: 'GET',
        path: '/users',
        pre: {
            assign: 'Test',
            method: async (request, h) => {
               console.log('Pre route is executed.');
               return "test data";
            }
        },
        handler: userController.getUsers,
        options: {
            auth: 'jwt-auth'
        }
    },
])

But when I execute the code, it is not executing the pre route method. When the pre route handler is included, it is always returning 404 not found response. Without it, it is working. What is wrong with my code and how can I fix it?



Solution 1:[1]

According to the "pre documentation", "pre" should be placed inside of the "options" property and should be an array

Here is an example how what it should look like for your code:

server.route([
  {
    method: 'GET',
    path: '/users',
    handler: userController.getUsers,
    options: {
      auth: 'jwt-auth',
      pre: [{
        assign: 'Test',
        method: async (request, h) => {
          console.log('Pre route is executed.');
          return "test data";
        }
      }]
    }
  },
])

You can get access to your "pre" data in the handler like this: const data = req.pre.Test

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akazakou