tvs tvs - 3 months ago 10
Perl Question

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

I'm trying to get a response data back from a perl CGI script:

I have the following JavaScript code:

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)
});


and this perl script:

#/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);
}


but I'm only getting this (I'm using Chrome's Web Developer Tools) and no data:

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


I'm sure the perl script works ok, here's the output of testing it from the command line:

# 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"]%


Anyone knows how to get the data response back to the js script? Thanks in advance for any help!

tvs tvs
Answer

I finally solved this, I'm posting my solution here as it might be relevant for other people having a similar problem.

The problem was twofold:

  1. I was printing an additional HTML header from the Perl script that make the JSON data wrong
  2. I haven't used response.json() within the premise to get the JSON data

Here's the fixed code:

JavaScript code:

    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 code:

#/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);
}
Comments