为什么Fetch API fetch()总是抛出异常?

时间:2019-12-12 00:02:34

标签: javascript apache ssl cors

我正在尝试从跨域服务器检索图像。我在WAMP堆栈服务器上使用自签名证书,但是无论我使用哪个标头,fetch()总是在飞行前检查后引发异常。以下是从chrome获取的请求/响应标头:

Yes

以下是调用fetch()的javascript代码:

General
Request URL: https://starlightproductions.ddnsfree.com/clientgalleries/michael.laver.suncorp.com.au/Snapper/holycrap.jpg
Request Method: OPTIONS
Status Code: 401 Unauthorized
Remote Address: 220.237.95.254:443
Referrer Policy: strict-origin

Response Headers
Connection: Keep-Alive
Content-Length: 381
Content-Type: text/html; charset=iso-8859-1
Date: Wed, 11 Dec 2019 23:28:36 GMT
Keep-Alive: timeout=5, max=100
Server: Apache
WWW-Authenticate: Basic realm="Client Only"
X-Frame-Options: SAMEORIGIN

Request Headers
Date: Wed, 11 Dec 2019 23:28:36 GMT
Keep-Alive: timeout=5, max=100
Server: Apache
WWW-Authenticate: Basic realm="Client Only"
X-Frame-Options: SAMEORIGIN
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization,content-type
Access-Control-Request-Method: GET
Connection: keep-alive
Host: starlightproductions.ddnsfree.com
Origin: http://dev.qwikfoto.com
Referer: http://dev.qwikfoto.com/
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36

以下是映像所在目录中.htaccess的标题:

let hdr = new Headers();

hdr.append(\'Content-Type\', \'application/octet-stream\');
hdr.append(\'Accept\', \'application/octet-stream\');
hdr.append(\'Authorization\', \'Basic \' + window.btoa(\'' . $xrefrec['ftp_username'] . ':' .
        $xrefrec['ftp_password'] . '\'));
hdr.append(\'Origin\',\'http://dev.qwikfoto.com\');

const myresponse = await fetch(document.getElementById(thm.photo_id).href, {
    mode: \'cors\',
    credentials: \'include\',
    method: \'GET\',
    headers: hdr
});

我已经为此工作了好几天。我什至尝试使用强制使用http 200响应代码 apache配置文件中的RewriteRule指令。非常感谢您的帮助。

谢谢

1 个答案:

答案 0 :(得分:0)

问题似乎出在您的自签名证书上。

对于fetch和SSL,fetch的行为与用户使用浏览器时的行为类似,这意味着它不允许从无效或自签名证书中获取资源,除非用户采取措施告诉浏览器可以这样做。

如果您要构建一个面向用户的网站,我的猜测是您将无法让用户采取手动步骤来允许浏览器执行此操作。

我最好的建议是使用Let's Encrypt之类的东西而不是自签名证书。