json - Perl CGI 在帖子中使用 JSON 传递变量

标签 json perl post cgi

我对让下面的工作感到茫然,并且已经没有想法了。我之前成功使用过这个设置,但在两个脚本之间有一个 JS 脚本,我目前无法使用该实现。

第一个脚本用于通过 perl 脚本从用户那里收集数据,它应该将数据发送到脚本二的 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";
}

脚本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"; 

输出:
#perl stager.pl 
Received reply:  was received

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

在此先感谢您的帮助。

最佳答案

来自 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');

因此,如果您想更改服务器以使用现有客户端,请使用
my $local = $cgi->param("POSTDATA"); 
如果要更改客户端以使用现有的服务器端,则需要创建一个“表单”
use HTTP::Request::Common qw( POST );

my $req = POST($server_endpoint,
   Content_Type => 'application/json',
   Content => [ name => $post_data ],
);
如果你有选择,前者(改变客户端)更简单。

关于json - Perl CGI 在帖子中使用 JSON 传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19610312/

相关文章:

javascript - 将给定字符串转换为 Json 对象 Javascript

Javascript 对象到格式化字符串

perl - 在 Perl 中,如何将此 CSV 字符串中的字段放入不带空格的数组中?

python - 使用 Python 对文件夹中的多个文件同时运行 perl 脚本

regex - 为什么 regcomp 在 perl 5.16.2 中比 perl 5.8.8 慢?

Javascript Lossy PNG图像压缩库

php - 如何获取 json 对象中数组的长度?

ajax - 如何在所有ajax请求中发送 token

post - 无法在 LISP hunchentoot 中获取帖子

Java - 在帖子后读取cookie