arwarner arwarner - 2 months ago 20
Perl Question

How to create a Perl API to pass data back to an angularjs $http request?

I'm using angular 1.5.7 and perl 5.16.2. I don't have the ability to use any external libraries or switch tools - I'm stuck just using what's included with these two.

The angular controller is making calls to a perl file. I'm able to make POST requests successfully, and my GET requests are returning status 200 but aren't showing the data that I am expecting to see. Right now I'm just working with a simple example to try and narrow down where things are going wrong, and I think I just don't know the format to return values from the perl file.

My controller GET method looks like so:

$http({
method : "GET",
url : "filename.pl",
params:{}
}).then(function successCallback(response) {
console.log(response.records);
}, function errorCallback(response) {
console.log(response);
});


and the perl code being called in filename.pl is:

my $string = q{{"records":{"2":{"City":"México D.F.","Country":"Mexico","Name":"Ana Trujillo Emparedados y helados"},"1":{"Name":"Alfreds Futterkiste","Country":"Germany","City":"Berlin"}}}};

return $string;


The string is just a dummy variable to see if passing things back works - it won't be the final data. I have verified it is valid JSON as well. Here's what the response from the server looks like:

{"data":"","status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"glwizardutils.esp","params":{"FUNCTION":"initcheckboxes","CONTEXTID":"432"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}


The data field is totally blank, and the response field doesn't work at all. I can verify it's hitting the perl file - like I said, POST requests work fine and I included some printouts that verify it's in the correct method, but it's just not returning anything. What should I be doing here instead to get this to work?

mob mob
Answer

If filename.pl is invoked with HTTP, then it should be writing an HTTP response to standard output. At a minimum:

print "HTTP/1.1 200 OK\n";
print "Content-type: application/json\n";
print "\n";

my $string = q{{"records":{"2":{"City":"México ..."}}}};
print $string;

Several frameworks and modules exist in Perl and virtually every other language to handle the repetitive aspects of writing a proper response, which you will want to look into as your Perl server-side script gets more demanding.

Comments