1

Is there a way to denote a POST parameter as optional in Perl using Mojolicious Lite? For instance, is there a way to make the server not return 404 if param2 is not defined in the request body?

post "/my_post" => \&render(post_callback);

sub post_callback {
    my ($mojo) = @_;
    my $param1 = $mojo->param("param1");
    my $param2 = $mojo->param("param2");
}
Danny Sullivan
  • 3,626
  • 3
  • 30
  • 39
  • 3
    Pretty sure it doesn't. It just sets `param2` to `undef`. If you're getting 404 it's because your callback isn't rendering anything. – Sobrique Jul 06 '15 at 12:26
  • If it's routed to the correct callback shouldn't it always return something besides 404? My problem is that it doesn't even appear to be routed to the correct callback. Though if I were to specify both ```param1``` and ```param2``` it would be routed to ```post_callback``` and return 200. – Danny Sullivan Jul 06 '15 at 12:31
  • 1
    No. Mojolicious renders something when it gets told to. Sometimes it does this implicitly. Try adding: `$mojo -> render ( text => "It worked" );` at the end of your callback. – Sobrique Jul 06 '15 at 12:33
  • Excellent, thanks very much for your help! – Danny Sullivan Jul 06 '15 at 12:50
  • If that solved it, can I suggest adding a quick summary answer for the benefit of future readers? – Sobrique Jul 06 '15 at 13:03
  • 1
    Sure thing, standby... – Danny Sullivan Jul 06 '15 at 13:19

2 Answers2

1

My problem was that I misunderstood how mojolicious was routing to the callback. The following code works with both parameters being optional:

#!/usr/bin/env perl
use strict;
use warnings;
use Mojolicious::Lite;

post '/' => sub {
    my ($mojo) = @_;
    my $param1 = $mojo->param("param1");
    my $param2 = $mojo->param("param2");
    $mojo->render(text => "param1: $param1, param2: $param2");
};

app->start;

If you run this using: ./my_server.pl daemon you will be able to send POST requests with any combination of parameters.

Danny Sullivan
  • 3,626
  • 3
  • 30
  • 39
1

In a post, I prefer not to use parameters but post all parameters in one JSON string. The mojolicous post-action will receive the json-string as a hash reference.

Example:

# The posted data looks like:
# '{ "username": "rob", "password": "secret" }'
#
sub authenticate {
    my $self = shift;
    my $jsonHash = $self->req->json ;
    $self->render( text => Dumper($jsonHash)) ;
}

With curl it is easy to test the post:

curl -X POST -d '{ "username": "rob", "password": "secret" }' http://hp-probook:3000/users/authenticate
Rob Lassche
  • 841
  • 10
  • 16