Perl CGI使用JSON在post中传递变量

Mat*_*zle 3 perl post json cgi

我无法让下面的工作让你失去了想法.我之前使用过这个设置但成功但在两个脚本之间有一个JS脚本,我目前无法使用该实现.

第一个脚本用于通过perl脚本从用户收集数据,它应该将数据发送到脚本2的CGI参数,但它要么不传递值,要么是空的.我确实得到200 HTTP响应,因此在第二个脚本上执行不是问题.

脚本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";
}
Run Code Online (Sandbox Code Playgroud)

脚本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"; 
Run Code Online (Sandbox Code Playgroud)

输出:

#perl stager.pl 
Received reply:  was received
Run Code Online (Sandbox Code Playgroud)

所以接收到200并且$ local变量为空.我将其打印到日志文件中并插入了一个空行.

在此先感谢您的帮助.

Sui*_*uic 7

来自CGI,

如果POSTed数据不是application/x-www-form-urlencoded或multipart/form-data类型,则不会处理POSTed数据,而是在名为POSTDATA的参数中按原样返回.要检索它,请使用以下代码:

my $data = $query->param('POSTDATA');
Run Code Online (Sandbox Code Playgroud)

因此,如果要更改服务器以使用现有客户端,请使用

my $local = $cgi->param("POSTDATA"); 
Run Code Online (Sandbox Code Playgroud)

如果要更改客户端以使用现有服务器端,则需要创建"表单"

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

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

如果您有选择,前者(更改客户端)更简单.