Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Express中的内容安全策略报告空对象_Express_Content Security Policy - Fatal编程技术网

Express中的内容安全策略报告空对象

Express中的内容安全策略报告空对象,express,content-security-policy,Express,Content Security Policy,我的web应用在后端使用Node.js和Express。当违反内容安全策略(CSP)时,报告URI报告一个空对象。我的后端中的代码如下所示: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(helmet({ contentSecurityPolicy: { directives: { // some policies here re

我的web应用在后端使用Node.js和Express。当违反内容安全策略(CSP)时,报告URI报告一个空对象。我的后端中的代码如下所示:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      // some policies here
      reportUri: ["/my_amazing_csp_report_parser"],
    },
  },
}));

app.use('/my_amazing_csp_report_parser', (req, res, next) => {
  console.log(req.body);
  next();
})

我在上一篇文章中读到,报告URI应该报告一个完整的JSON对象。但是我的
console.log(req.body)返回一个空对象。我想知道我是否用
app.use(bodyParser.urlencoded({extended:true}))解析JSON对象时出错
app.use(bodyParser.json())

我不使用React,因此我无法给出明确的代码。但我可以解释发生了什么

CSP报告与从
发送的数据不同。
数据的内容类型为“application/x-www-form-urlencoded”或“multipart/form data”,用于将对列表发送到服务器。这些数据可以是二进制(文件)或URL编码的,因此需要使用
bodyParser.urlencoded()

CSP报告以“application/json”MIME类型发送,没有名称/值对,只有
body
。因此,bodyParser.urlencoded({extended:true})将为您提供空的body,您需要使用如下内容:

*
我从未遇到过“应用程序/csp报告”的内容类型,也从未使用过,这取决于您。至少不是这样。这是CSP规范中报告的MIME类型,抱歉

不要忘记返回“204无内容”状态代码


这是一个如何使用winston logger获取报告的示例,但我不知道它是否有效。

Hi@granty,工作非常出色。非常感谢。我试图理解为什么我必须返回
“204无内容”
?由于它是一个报告URI,我认为我不需要结束它,因为没有客户端等待响应。HTTP是一个请求-应答协议,每个请求都应该有应答。如果在超时时间内没有回复,浏览器会认为出现了问题,并将重新发送请求。204代码表示服务器已成功获得请求,但无意发送任何数据作为响应。
app.use('/report-violation', bodyParser.json({ type: 'application/json' }));  # for old browsers
app.use('/report-violation', bodyParser.json({ type: 'application/reports+json' })); # for report-to directive
app.use('/report-violation', bodyParser.json({ type: 'application/csp-report' }));  # for report-uri directive
app.use('/report-violation', (req, res) => {
  // handle req.body
  res.status(204).end()
});