如何加载来自API的第三方图像



我一直在寻找各种解决方案来解决这个问题,但没有一个对我有效。

我正在制作一个显示新闻文章的网站。

获取数据的JS代码

async function fetchNewsData(region) {
try {
const request = await fetch(
`https://newsapi.org/v2/top-headlines? 
country=${region}&category=business&apiKey=${API_KEY}`);
const response = await request.json();
if (response.status !== "ok") throw new Error("Something went wrong!");
return response;
} catch (err) {
console.error(err);
}
}

API响应

{
"author": "Cointelegraph By Brian Newar",
"title": "Large institutions sold $5.5B in BTC since May — and we're still here",
"description": "Massive sell-offs from institutions appear to have been the driving 
force behind the drop in Bitcoin price since May, according to an analyst from Arcane 
Research.",
"urlToImage":"https://images.cointelegraph.com/images/1200_aHR0cHM6Ly
9zMy5jb2ludGYWRzLzIwMjItMDcvZmUFlLTg4NDQtMzFjZmY0MjQ2OWY5LmpwZWc=.jpg",
"publishedAt": "2022-07-22T02:44:01Z",
"content": "Since May 10, as much as 236,237 Bitcoin (worth $5.452 billion) has been 
sold by large institutions mostly as a result of forced selling. rnA Twitter thread 
from Arcane Research analyst Vetle Lunde d… [+3128 chars]"
},

当我使用JS动态显示上述数据时,一切都很好,但我在渲染图像时遇到CSP错误。我该怎么修?

我尝试过的解决方案:

  1. 代理服务器(heroku(它没有工作,不是一个好的解决方案
  2. img标记<img src="urlToImage" crossorigin="anonymous" />中的交叉原点属性
  3. 我读过MDN关于CORS的文章,但没有一篇对我有帮助,它让我不知所措

我使用的META标签

`meta(http-equiv="Content-Security-Policy" content="default-src 
'self'; font-src 'self' *; img-src 'self' data: https://*; script- 
src 'self'; style-src 'self' https://fonts.googleapis.com 
https://fonts.gstatic.com; frame-src 'self';")`

我得到的错误:

**Refused to load the image '<URL>' because it violates the following Content Security 
Policy directive: "img-src 'self' data:".
stocknews:1 Refused to load the image 'https://images.moneycontrol.com/static- 
mcnews/2021/08/Sensex_Nifty-1-770x433.jpg' because it violates the following Content 
Security Policy directive: "img-src 'self' data:".**

当我使用包裹打包器并提出请求时,我可以加载图像而不会出现任何错误。但没有包裹,我得到CSP错误。为什么

我希望有一个安全的解决方案,而不是一些棘手的解决方案来解决这个问题。

谢谢。

您的HTML中有一个<meta>标记,其中包含Content-Security-Policy吗?这个错误似乎与这个标签有关,其中图像的安全策略是:

<meta http-equiv="Content-Security-Policy"
content="img-src 'self' data:;">

尝试将其更新为:

<meta http-equiv="Content-Security-Policy"
content="img-src 'self' data: https://*;">

(或者代替*,您可以包括所有已知的域,包括来自的图像(

有关此标签的更多信息

这是因为内容安全策略,您需要更改您希望允许图像或其他数据的域

在你的情况下,你可以这样做

数据:images.contellegraph.com;

或者如果您想允许来自任何地方的图像,则使用*而不是特定地址,但出于安全考虑,不建议使用

最新更新