【发布时间】: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