【问题标题】:Cannot load jQuery because it violates Content Security Policy [closed]无法加载 jQuery,因为它违反了内容安全策略 [关闭]
【发布时间】:2021-01-13 02:21:17
【问题描述】:

我在 node + express 上写了一个服务器。准备页面以进行渲染,使用 Jquery 在 JS 中编写脚本。但是 Jquery 由于某种原因无法加载页面。这是一个常见的情况,在我在 WebSockets 上编写 ToDo 应用程序之前,我遇到了同样的错误。问题是什么以及如何解决?请帮忙。 错误: 拒绝加载脚本“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js”,因为它违反了以下内容安全策略指令:“script-src 'self'” .请注意,'script-src-elem' 没有显式设置,因此 'script-src' 用作备用。

我尝试从其他来源添加不同的元标记,但没有帮助。

【问题讨论】:

标签: javascript node.js express content-security-policy


【解决方案1】:

Content Security Policy 是一个相当大的话题,让我迷茫了一阵子。

我最终使用了helmet,其中包括定义内容安全策略设置的能力,如下所示:

app.use(
    helmet({
        contentSecurityPolicy: {
            directives: {
                defaultSrc: ["'self'"],
                scriptSrc: ["'self'", "https://maps.googleapis.com", "https://www.google.com", "https://www.gstatic.com"],
                connectSrc: ["'self'", "https://some-domain.com", "https://some.other.domain.com"],
                styleSrc: ["'self'", "fonts.googleapis.com", "'unsafe-inline'"],
                fontSrc: ["'self'", "fonts.gstatic.com"],
                imgSrc: ["'self'", "https://maps.gstatic.com", "https://maps.googleapis.com", "data:", "https://another-domain.com"],
                frameSrc: ["'self'", "https://www.google.com"]
            }
        },
    })
);

我发现使用这种语法定义规则的能力对我来说更容易,并帮助我更多地了解内容安全策略。

Helmetexpress.js security docs 和这个node best practises blog 中被提及。

我的特殊情况的更多背景信息记录在答案I posted here中。

【讨论】:

    【解决方案2】:

    这是更好的错误消息之一,因为它相当具体:您已将页面的Content Security Policy 设置为script-src: 'self'script-src 策略控制哪些源是 JavaScript 的有效源,self 意味着只有与文档本身同源的源才有效。

    您可以通过以下三种方式之一解决此问题:

    1. 修改与页面一起返回的Content-Security-Policy 标头,使其不包含script-src: self,或者

    2. 修改Content-Security-Policy 标头添加https://cdnjs.cloudflare.com 作为有效源(列表以空格分隔),如下所示:

      Content-Security-Policy: 'self' https://cdnjs.cloudflare.com

    3. 使用与页面同源的本地 jQuery 副本

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2017-11-26
      相关资源
      最近更新 更多