无法加载 jQuery,因为它违反了内容安全策略

Cannot load jQuery because it violates Content Security Policy

我在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' 用作后备。

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

这是更好的错误消息之一,因为它相当具体:您设置了 Content Security Policy for the page to script-src: 'self'. The script-src 策略控制哪些来源是 JavaScript 的有效来源,并且 self 意味着只有与文档本身来源相同的来源才有效。

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

  1. 修改随页面返回的 Content-Security-Policy header 以不包含 script-src: self,或

  2. 修改 Content-Security-Policy header 添加 https://cdnjs.cloudflare.com 作为有效来源(列表为 space-separated),如下所示:

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

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

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"]
            }
        },
    })
);

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

Helmet is mentioned in the express.js security docs and this node best practises blog.

我的具体情况的更多背景信息记录在答案