我正在尝试从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的网络开发者工具)并且没有数据:
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脚本?在此先感谢您的帮助!
答案 0 :(得分:3)
您没有在回调链中传递数据。您必须return
来自then()
处理程序的内容,如果您希望它出现在以下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
语句,它隐式返回undefined
,这就是您在下一个处理程序中看到的内容。
如果您没有进行任何额外的异步工作,通常不需要多次调用then()
。
答案 1 :(得分:0)
我终于解决了这个问题,我在这里发布我的解决方案,因为它可能与其他有类似问题的人有关。
问题是双重的:
这是固定代码:
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);
}