On 09/15/2013 01:33 PM, Matt Price wrote:
> Of course! Just do the following:
>
> $self->req->json
>
> Returns a hashref.
Thanks ... I think I've been beating my head against either pilot error
or a bug then. I can't figure out which at the moment.
I was using Mojolicious::UserAgent to try to do the post, and no
parameters were getting through at all. Then, for laughs, I switched to
LWP::UserAgent, and it worked.
Server:
#!/usr/bin/perl -w
use strict;
use Mojolicious::Lite;
use JSON;
use XML::Simple;
use Data::Dumper;
post '/' => sub {
my $self = shift;
my @params = $self->param;
my $content;
my ($output,$status,$json,$xml,$txt);
$json = JSON->new->allow_nonref;
# copy parameters into content hash
foreach my $p (@params) {
next if ($p =~ /_type/i);
$content->{$p} = $self->param($p);
}
my $text = "ok: ";
map {$text .= (sprintf "%s=%s, ",$_,$content->{$_})} @params;
$self->render(text => $text);
};
app->start(qw(daemon --listen http://*:3000));
Mojolicious::UserAgent client (call this
q.pl)
#!/usr/bin/perl
use strict;
use Mojo::UserAgent;
use Data::Dumper;
my ($res,$tx,$headers,$ua,$t);
$t = Mojo::UserAgent->new;
$tx = $t->post('
http://localhost:3000/' => json => { a => '1', b => '2'});
$res = $tx->res->body;
printf "result = %s\n ",Dumper($res);
LWP::UserAgent version (call this
p.pl)
#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use Data::Dumper;
my ($res,$tx,$headers,$ua,$t);
$t = LWP::UserAgent->new;
$tx = $t->post('
http://localhost:3000/' , { a => '1', b => '2'});
$res = $tx->content;
printf "result = %s\n ",Dumper($res);
Run the server, and then first the
q.pl code (Mojolicious::UserAgent)
landman@lightning:~$ ./
q.pl
result = $VAR1 = 'ok: ';
then the
p.pl code (LWP::UserAgent)
landman@lightning:~$ ./
p.pl
result = $VAR1 = 'ok: a=1, b=2, ';
But if I change the
q.pl to
r.pl by using
$tx = $t->post('
http://localhost:3000/' => form => { a => '1', b => '2'});
I get the expected result:
landman@lightning:~$ ./
r.pl
result = $VAR1 = 'ok: a=1, b=2, ';
Basically I am not sure if this is pilot error, a bug, or a
documentation ambiguity (c.f.
http://search.cpan.org/~sri/Mojolicious-4.37/lib/Mojo/UserAgent.pm#post
where the form
my $tx = $ua->post(
'
http://example.com' => {DNT => 1} => json => {a => 'b'});
is specifically indicated).
I was thinking this was a server side issue, but I am wondering if its
really a client side Mojo::UserAgent bug in docs or code ...). Still
could be pilot error, and I'd be happier if it were.
Joe
--
joe.l...@gmail.com