Fetch an API -> Uncaught (in promise) TypeError: Failed to fetch

问题描述 投票:0回答:1

我在获取 api 数据时遇到问题.. 这个 api -> https://resmush.it/api

我的请求在 Postman 上工作 但在我的网站上不工作我有这个错误:

未捕获(承诺)TypeError:无法获取

我的代码:

const params = {
    method: 'GET',
    mode: 'no-cors',
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json'
    }
};

fetch('http://api.resmush.it/ws.php?img=https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png&qlty=50', params)
    .then(reponseBis => reponseBis.json())
    .then(dataBis => console.log(dataBis));

感谢帮助!

javascript
1个回答
0
投票

EDIT似乎这个标题

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
造成了麻烦。如果删除它,代码应该可以工作

此元标记会将

HTTP
升级为
HTTPS
,但是您使用的 API 不提供服务
HTTPS

来自文档:

请注意,如果请求的资源实际上无法通过 HTTPS 获得,则请求将失败而不会回退到 HTTP。

------

Mixed Content: The page at 'https://www.mywebsite.com/page.php' was loaded over HTTPS, but requested an insecure resource 'http://api.resmush.it/ws.php?img=https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png&qlty=50'. This request has been blocked; the content must be served over HTTPS.

问题是这个链接

https://upload.wikimedia.org
HTTPS
,而
http://api.resmush.it
HTTP
。将 resmush 网址更改为
https://
或将维基媒体链接更改为
http://

--------

看看HTTP标头

使用 no-cors 只能用于将数据发布到不允许 cors 的 API。但这样做会返回一个空响应。你给的API允许cors,所以这个根本不需要。

Content-Type
标题应该是
Accept

const params = {
    method: 'GET',
    headers: {
        'accept': 'application/json'
    }
};

fetch('http://api.resmush.it/ws.php?img=https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png&qlty=50', params)
.then(response => response.json())
.then(json => console.log(json))
.catch(e => console.error(e));
{
  "src": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Google_Images_2015_logo.svg/1200px-Google_Images_2015_logo.svg.png",
  "dest": "http://par3.static.resmush.it/a95239e7e37bade3af9ca3b7eabb8f11/1200px-Google_Images_2015_logo.svg.png",
  "src_size": 48597,
  "dest_size": 19545,
  "percent": 60,
  "output": "json",
  "expires": "Thu, 06 Aug 2020 09:52:12 +0200",
  "generator": "reSmush.it rev.2.0.6.20200328"
}
© www.soinside.com 2019 - 2024. All rights reserved.