【问题标题】:javascript fetch: can't get POST response data from perl scriptjavascript fetch:无法从 perl 脚本获取 POST 响应数据
【发布时间】:2016-08-23 21:16:58
【问题描述】:

我正在尝试从 perl CGI 脚本中获取响应数据:

我有以下 JavaScript 代码:

    fetch('/test.pl', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: this.state.msgName,
        email: this.state.msgEmail
      })
    })
    .then((response) => {
        console.log("been here");
        console.log(response);
    })
    .then((responseData) => {
      console.log("been here 2");
      console.log(responseData);
    })
    .then((data) => {
      console.log("been here 3");
      console.log(data);
    })
    .catch((error) => {
      console.log("Failed!", error)
    });

还有这个 perl 脚本:

#/usr/bin/env perl
use strict;
use CGI;
use JSON;

my $q = new CGI;
my $json = new JSON;

if ($q->param)
{
  print $q->header();
  my $hash = $json->decode($q->param('POSTDATA'));
  print $q->header('application/json');
  my $msg = [ sprintf "data from %s received ok", $hash->{name} ];
  print $json->encode($msg);
}

但我只得到这个(我正在使用 Chrome 的 Web 开发者工具)并且没有数据:

 been here
 Response {type: "basic", url: "http://localhost/test.pl", status: 200, ok: true, statusText: "OK"…}
 been here 2
 undefined
 been here 3 
 undefined

我确定 perl 脚本可以正常工作,这是从命令行对其进行测试的输出:

 # curl -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"name":"uvw","email":"xyz"}' http://localhost/test.pl
 Content-Type: application/json; charset=ISO-8859-1

 ["data from uvw received ok"]%

有人知道如何将数据响应返回给 js 脚本吗?提前感谢您的帮助!

【问题讨论】:

    标签: javascript perl fetch


    【解决方案1】:

    您没有将数据传递到回调链中。如果您希望在下面的then() 中得到它,您必须从then() 处理程序中return

    function promiseOne() {
      return Promise.resolve(1)
    }    
    
    promiseOne()
      .then(one => { console.log(one) }) # 1
      .then(one => { console.log(one) }) # undefined
    
    promiseOne()
      .then(one => { console.log(one); return one }) # 1
      .then(one => { console.log(one) })             # 1
    

    由于第一个 then() 处理程序没有 return 语句,它隐式返回 undefined,这就是您在下一个处理程序中看到的内容。

    如果你不做任何额外的异步工作,你通常不需要多次调用then()

    【讨论】:

    • 好吧,如果我按照你说的做,我就没有'未定义'了,但是我仍然没有从 perl 脚本中得到响应数据
    • CGI 脚本有效吗?根据您自己的日志,您确实有一个 Response 对象
    • 是的,我已经通过命令行使用 curl 进行了测试并正确返回了数据(请参阅我在帖子末尾写的内容)
    【解决方案2】:

    我终于解决了这个问题,我在这里发布我的解决方案,因为它可能与其他遇到类似问题的人有关。

    问题是双重的:

    1. 我从 Perl 脚本中打印了一个额外的 HTML 标头,导致 JSON 数据错误
    2. 我没有在前提下使用response.json()来获取JSON数据

    这是固定代码:

    JavaScript 代码:

        fetch('/test.pl', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: this.state.msgName,
            email: this.state.msgEmail
          })
        })
        .then((response) => {
            response.json().then((data) => {
              console.log(data);
            });
    
            return(response);
          }
        })
    

    Perl 代码:

    #/usr/bin/env perl
    use strict;
    use CGI;
    use JSON;
    
    my $q = new CGI;
    my $json = new JSON;
    
    if ($q->param)
    {
      print $q->header();
      my $hash = $json->decode($q->param('POSTDATA'));
      # NEXT LINE REMOVED, IT WAS WRONG!!
      #print $q->header('application/json');
      my $msg = [ sprintf "data from %s received ok", $hash->{name} ];
      print $json->encode($msg);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多