javascript 获取:无法从 perl 脚本获取 POST 响应数据

javascript fetch: can't get POST response data from perl script

我正在尝试从 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脚本?在此先感谢您的帮助!

您没有将数据传递到回调链中。如果您希望在以下 then().

中使用 return 来自 then() 处理程序的内容
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 语句,它隐含地 returns undefined,这就是您在下一个处理程序中看到的。

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

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

问题是双重的:

  1. 我从 Perl 脚本打印了一个额外的 HTML header,导致 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);
}