gpt4 book ai didi

express - 加载被内容安全策略阻止的资源

转载 作者:行者123 更新时间:2023-12-02 10:43:27 26 4
gpt4 key购买 nike

我在浏览器的控制台中收到以下错误:

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico (“default-src”).

我在网上搜索发现应该使用下面的代码片段来修复此问题:

<meta http-equiv="Content-Security-Policy" content="default-src *;
img-src * 'self' data: https: http:;
script-src 'self' 'unsafe-inline' 'unsafe-eval' *;
style-src 'self' 'unsafe-inline' *">

我将其添加到我的前端 app.component.html 文件(我所有前端 View 的父模板)中,但这并没有按预期工作。

我也尝试过多种排列,但均无济于事。

我的前端位于localhost:4200,后端位于localhost:3000

下面是我的后端服务器(中间件)的代码片段:

app.use(cors());
app.options('*',cors());
var allowCrossDomain = function(req,res,next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.use(allowCrossDomain);

我现在还向我的后端(Express)服务器添加了以下中间件:

const csp = require('express-csp-header');

app.use(csp({
policies: {
'default-src': [csp.SELF, 'http://localhost:3000/', 'http://localhost:4200/' ],
'script-src': [csp.SELF, csp.INLINE],
'style-src': [csp.SELF],
'img-src': ['data:', 'favico.ico'],
'worker-src': [csp.NONE],
'block-all-mixed-content': true
}
}));

。 。 。但仍然没有解决问题。

这是屏幕截图:

enter image description here

我做错了什么以及如何解决它?

最佳答案

内容安全策略(CSP)是一种有助于防止跨站脚本(XSS)的机制,最好在服务器端处理;请注意,它也可以在客户端处理,利用 <meta> HTML 的标签元素。

配置并启用后,Web 服务器将返回相应的 Content-Security-Policy在 HTTP 响应 header 中。

您可能想在 HTML5Rocks 网站和 Mozilla 开发人员页面 here 上阅读有关 CSP 的更多信息。和 here .

Google CSP Evaluator是一个方便且免费的在线工具,可帮助测试您的网站或 Web 应用程序的 CSP。

在您的实例中,您可能需要添加以下行,而不使用 https: 强制使用 HTTPS 作为协议(protocol)。指令;
因为您的网站或应用程序(共享)无法通过 HTTPS 访问。

res.header('Content-Security-Policy', "img-src 'self'");

default-src 开头指令设置为none是开始部署 CSP 设置的好方法。

如果您选择使用Content-Security-Policy middleware for Express ,您可以按照下面的代码片段所示开始使用;

const csp = require('express-csp-header');
app.use(csp({
policies: {
'default-src': [csp.NONE],
'img-src': [csp.SELF],
}
}));

// HTTP response header will be defined as:
// "Content-Security-Policy: default-src 'none'; img-src 'self';"

请记住,CSP 是特定于案例或应用的,并且基于您的项目要求。

因此,您需要进行微调以满足您的需求。

关于express - 加载被内容安全策略阻止的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56386307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com