Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl CGI passing variable in post with JSON

Tags:

json

post

cgi

perl

I am at a loss for getting the below to work and have ran out of ideas. I have used this setup before with success but with a JS script in between the two scripts and I cant currently use that implementation.

The first script is used to collect data from a user via a perl script, and it should be sending the data to script two's CGI param, but it is either not passing the values or they are empty. I do get a 200 HTTP response so it is not an issue with execution on the second script.

Script 1:

#!/usr/bin/perl

        use LWP::UserAgent;

        my $ua = LWP::UserAgent->new;

        my $server_endpoint = "http://urlthatisaccessable.tld/script.pl";   

# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('content-type' => 'application/json');

# add POST data to HTTP request body
my $post_data = '{ "name": "Dan" }';
$req->content($post_data);

my $resp = $ua->request($req);
if ($resp->is_success) {
    my $message = $resp->decoded_content;
    print "Received reply: $message\n";
}
else {
    print "HTTP POST error code: ", $resp->code, "\n";
    print "HTTP POST error message: ", $resp->message, "\n";
}

Script 2:

#!/usr/bin/perl
# Title Processor.pl

use CGI;

my $cgi = CGI->new;                  
my $local = $cgi->param("name");         

print $cgi->header(-type => "application/json", -charset => "utf-8");
print "$local was received"; 

Output:

#perl stager.pl 
Received reply:  was received

So the 200 is received and the $local variable is empty. I printed it to a log file and a blank line was inserted.

Thanks in advance for the help on this one.

like image 982
MattSizzle Avatar asked Jan 13 '23 01:01

MattSizzle


1 Answers

From CGI,

If POSTed data is not of type application/x-www-form-urlencoded or multipart/form-data, then the POSTed data will not be processed, but instead be returned as-is in a parameter named POSTDATA. To retrieve it, use code like this:

my $data = $query->param('POSTDATA');

So if you want to change the server to work with the existing client, use

my $local = $cgi->param("POSTDATA"); 

If you want to change the client to work with the existing server-side, you'll need to create a "form"

use HTTP::Request::Common qw( POST );

my $req = POST($server_endpoint,
   Content_Type => 'application/json',
   Content => [ name => $post_data ],
);

If you have a choice, the former (changing the client) is simpler.

like image 66
Suic Avatar answered Jan 26 '23 02:01

Suic