我試圖得到迴應數據從一個Perl CGI腳本後退POST響應數據:JavaScript抓取:無法從Perl腳本
我有以下的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腳本?預先感謝任何幫助!
好吧,如果我做你說什麼我沒有做「不確定」了,但我仍然沒有從Perl腳本獲得響應數據 – tvs
是的CGI腳本工作?根據您自己的日誌,您確實有'Response'對象 – slezica
是的,我已經通過命令行使用curl進行了測試並正確返回數據(請參閱我在發佈結束時寫的內容) – tvs