繁体   English   中英

拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src 'self'”。?

[英]Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'".?

我正在尝试在我的项目中使用内联脚本,但我不断收到此错误:'拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src'self'”。 启用内联执行需要“unsafe-inline”关键字、哈希(“sha256-hyQXPyDjuL7UGCz8hPIbJ2ZzKwE8uqNzvUJB9/9T6jc=”)或随机数(“nonce-...”)。

我在这里查看了许多其他类似的问题,他们都说这与元标记有关,并包含以下内容: <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />

但这并没有什么区别,我已经从我的<head>中删除了所有元标记,但我仍然得到同样的错误。 除了<head>之外,这个问题可能来自哪里? 我用 express-generator 创建了我的项目,但我在我的任何文件中都找不到任何 CSP。

我完全不知道是什么阻止了内联脚本,如果我可以提供任何代码,请告诉我,但是看到我不知道是什么原因造成的,我不知道要提供什么代码

CSP 指令未设置在元标记中,而是设置在 HTTP 标头中。

既然你用node.jsexpress标签标记了这个问题,下面是一个在 express 中设置 CSP 标头的示例:

const express = require("express");
const app = express();
const port = 8080;

app.get("/", (req, res) => {
    res
        .set("Content-Security-Policy", "default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'")
        .send("<html><head></head><body></body></html>");
})

app.listen(port, () => {
    console.log("Listening on port %s", port);
});

然后您可以在响应标头中看到 CSP:

curl -v http://localhost:8080
* Rebuilt URL to: http://localhost:8080/
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.53.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Security-Policy: default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'
< Content-Type: text/html; charset=utf-8
< Content-Length: 39
< ETag: W/"27-ghawzGh2y9RPAcFY59/zgzzszUE"
< Date: Tue, 17 Nov 2020 00:01:04 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
< 
* Connection #0 to host localhost left intact
<html><head></head><body></body></html>

对我来说问题是cheerio版本。 从 1.0.0-rc.12 到 1.0.0-rc.5 之后工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM