对于我的小Javascript应用程序,我使用CGI编写了服务器端API函数。
我让它非常简单,完整的示例脚本看起来像这样:
#!/usr/bin/env perl
use strict; use warnings; use 5.014;
use CGI;
use JSON;
use Data::Dumper;
my $q = new CGI;
my %p = $q->Vars;
_api_response();
sub _api_response {
my ( $error ) = @_;
my $res;
my $status = 200;
my $type = 'application/json';
my $charset = 'utf-8';
if ( $error ) {
$status = 500;
$res->{data} = {
status => 500,
};
$res->{error} = {
error => 'failure',
message => $error,
detail => Dumper %p,
};
} else {
$res->{data} = {
status => 200,
};
}
print $q->header(
-status => $status,
-type => $type,
-charset => $charset,
);
my $body = encode_json( $res );
print $body;
}
当我用fetch
从JS脚本调用它时,它没有得到响应体。如果我从开发人员工具/网络检查,它也没有响应体。如果我在浏览器中输入相同的URL,它会显示JSON主体。如果我用curl
作为
curl -v 'https://example.com/my_api?api=1;test=2;id=32'
响应似乎也有正确的主体:
< HTTP/2 200
< date: Mon, 13 Sep 2021 14:04:42 GMT
< server: Apache/2.4.25 (Debian)
< set-cookie: example=80b7b276.5cbe0f250c6c7; path=/; expires=Thu, 08-Sep-22 14:04:42 GMT
< cache-control: max-age=0, no-store
< content-type: application/json; charset=utf-8
<
* Connection #0 to host example.com left intact
{"data":{"status":200}}
为什么fetch
不认为它是一个身体?
为了完整起见,我还包括了JS部分:
async function saveData(url = '', data = {}) {
const response = await fetch(url, {
method: 'GET',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
});
console.log(response); // body is null
return response.json();
}
使用函数as:
saveData('https://example.com/my_api?api=1;test=2;id=32', { answer: 42 })
.then(data => {
console.log(data);
})
.catch( error => {
console.error( error );
});
在控制台我看到错误:
SyntaxError: Unexpected end of input
这个错误的一个可能的原因是空的JSON字符串。
我能够重现您的问题,然后我能够修复它。
这是一个CORS问题。您需要在前端和后端同时启用CORS。
在前端,您需要在页面的<head>
中使用元标记设置内容安全策略:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost">
(不要忘记将localhost
更改为您的实际域名)
在背面,你需要添加CORs标题:
print $q->header(
-status => $status,
-type => $type,
-charset => $charset,
-access_control_allow_origin => '*', # <-- add this line
);
作为旁注,您传递给fetch
的设置都不是必需的。因为你在等待响应,然后返回另一个承诺,所以真的没有理由让它成为一个async函数。
在您准备使用未使用的data
参数之前,以下代码就足够了:
function saveData(url = '', data = {}) {
return fetch(url).then(response=>response.json());
}
response.json()
也必须是await
尝试return await response.json();
,而不是return response.json();