如何在express和bodyParser中将application / csp-report接受为json?

toy*_*toy 4 javascript json content-type express body-parser

我正在尝试编写一个中间件来接受来自浏览器的CSP报告。浏览器问题application/csp-reportContent-Type。正在发布的请求是JSON格式。目前,我习惯于bodyParser.text接受那种Content-type。但是我认为application/csp-report在bodyParser中可能有更好的方法接受JSON。

这就是我现在正在做的事情。

app.use(bodyParser.json());
app.use(bodyParser.text({type: 'application/csp-report'}));
Run Code Online (Sandbox Code Playgroud)

我的问题是我如何接受JSON请求有效载荷Content-Type application-csp-report

Bar*_*ard 5

由于它实际上是JSON,因此您可以像这样通知Express:

app.use(bodyParser.json({type: 'application/csp-report'}));
Run Code Online (Sandbox Code Playgroud)

但是请注意,有些浏览器使用application / csp-report,有些使用application / JSON,所以我将两者都设置了:

app.use(bodyParser.json({type: 'application/json'}));
app.use(bodyParser.json({type: 'application/csp-report'}));
Run Code Online (Sandbox Code Playgroud)

如果有帮助,我可以在此处为(非常简单的)节点报告服务编写代码:https : //www.tunetheweb.com/security/http-security-headers/csp/


Iva*_*anM 5

除了@Barry的答案之外,您还可以更具体地设置端点路径:

app.use('/report-violation', bodyParser.json({ type: 'application/json' }));
app.use('/report-violation', bodyParser.json({ type: 'application/csp-report' }));
app.use('/report-violation', (req, res) => {
  // handle req.body
});
Run Code Online (Sandbox Code Playgroud)