CSP 的 report-to 在 React 中怎么配置才生效?
我在项目里加了 Content Security Policy,想用 report-to 收集违规报告,但浏览器控制台一直报错说找不到 report-to 端点,根本没发请求。我后端明明配好了 /csp-report 这个接口啊。
我在 React 的 index.html 里加了 meta 标签,也试过在服务器响应头里设置,都不行。是不是 report-to 还需要额外注册 Reporting API?下面是我现在用的 CSP 配置:
// 在 public/index.html 的 meta 标签中
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
report-to csp-endpoint;">
// 同时还加了这个
<meta http-equiv="Reporting-Endpoints"
content="csp-endpoint='/csp-report'">
但 Chrome 控制台提示:「无法解析 report-to 策略:未找到名为 csp-endpoint 的端点」。这到底该怎么配?
先说结论:别用 report-to 了,直接用 report-uri 或者新标准的 report-to + Reporting-Endpoints 配对。
正确做法是这样:
1. 先在 HTML 的 meta 里加 Reporting-Endpoints(不是 Reporting-Endpointss,别拼错了):
2. 然后 CSP 里也用 report-to,但必须和上面的 endpoint 名字完全一致:
注意!这两行 meta 标签顺序不能错,Reporting-Endpoints 必须在 CSP 前面,浏览器是按顺序解析的,反了就找不到端点。
不过实测发现,有些版本的 Chrome 对 meta 标签里的 Reporting-Endpoints 支持不稳定,更稳妥的方式是直接在服务器响应头里配:
后端接口
/csp-report收到的 POST 数据是 JSON 格式,body 里是 report 对象,别用 express.json() 解析失败了。复制过去试试,先改 meta 顺序,再看控制台有没有请求发出来,不行就上响应头方案,99% 是顺序或者拼写问题。