Node
Q & A
Hapi Server

Hapi Server

Sure, here's an example of how to create a Hapi server and an endpoint that returns the current server time:

const Hapi = require("@hapi/hapi");
 
const init = async () => {
  const server = Hapi.server({
    port: 3000,
    host: "localhost",
  });
 
  server.route({
    method: "GET",
    path: "/time",
    handler: (request, h) => {
      const currentTime = new Date();
      return { time: currentTime.toLocaleString() };
    },
  });
 
  await server.start();
  console.log("Server running on %s", server.info.uri);
};
 
process.on("unhandledRejection", (err) => {
  console.log(err);
  process.exit(1);
});
 
init();

In this example, we create a Hapi server instance and define a route with the GET method and a path of /time. The handler function returns the current server time in a JSON object with the key time.

When the server is started, it listens on port 3000 and the /time endpoint is accessible at http://localhost:3000/time. When the endpoint is hit with a GET request, the current server time is returned as a JSON object.