Performing get request with Perl Dancer web framework

Here, we are going to learn how to perform get request with Perl Dancer web framework?
Submitted by Godwill Tetah, on December 11, 2020

In this tutorial, we will learn how to make a "get" request in Perl Dancer web framework? In our last tutorial, I made an introduction to Perl Dancer web framework. Our focus today is on the "get" http method.

The http "get" method is used to make a request or retrieve information. This particular method is accompanied by a route which when accessed by a web browser, the server provides the information available on that route.

We will create a web app that has a home page and an about page where if a user accesses the default route or makes a get a get request to any of the routes, it will serve the information provided on that route.

Let's quickly write some code to understand what I'm talking about.

index.pl

#implementation of the get method

use Dancer;
get '/' => sub {
    return "This is the home page";
};

get '/about' => sub {
    return "hello, i am called includehelp and i help people online!";
};

dance;

The following points explain the code above;

  • To begin using the Dancer functionalities, we must call Dancer in our code. This is done by "use Dancer".
  • Creating a get method begins with the word get which is followed by the route in a single quote and next by the route handler. In Perl Dancer, the route handler is a subroutine. Therefore, what the subroutine returns is what will be served to anyone who accesses that route. As you can see, the route is just a slash / which signifies the default route.
  • The subroutine returns some text.
  • The second get method has an "about" route which returns information about that route whenever it is requested.
  • The code finally ends with dance. Always remember the semi colons at the end of the curly brackets.

To execute the code above, open a command prompt window from your project directory and run the command perl index.pl where index.pl is the name of my file.

get request with Perl Dancer web framework (1)

If everything was successful, you will get a similar output like mine. Open the web browser and move to localhost:3000 to see the output.

Output:

get request with Perl Dancer web framework (2)

http://localhost:3000/about

get request with Perl Dancer web framework (3)



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.