How to accept application/csp-report as json in express and bodyParser?
Asked Answered
H

2

5

I'm trying to write a middleware to accept CSP report from browser. Browser issues application/csp-report as Content-Type. The request being posted is JSON format. Currently I use bodyParser.text to accept that Content-type. But I thought there might be a better way to accept application/csp-report as JSON in bodyParser.

Here's what I'm doing right now.

app.use(bodyParser.json());
app.use(bodyParser.text({type: 'application/csp-report'}));

My question is how do I accept JSON request payload with Content-Type application-csp-report?

Heteroclite answered 22/3, 2016 at 20:53 Comment(0)
C
13

Since it is actually JSON you can inform Express of that fact like this:

app.use(bodyParser.json({type: 'application/csp-report'}));

Note however some browsers use application/csp-report, some application/json so I set both:

app.use(bodyParser.json({type: 'application/json'}));
app.use(bodyParser.json({type: 'application/csp-report'}));

If it helps I've code for a (very simple) Node Report service here: https://www.tunetheweb.com/security/http-security-headers/csp/

Casebound answered 28/3, 2016 at 19:21 Comment(0)
S
5

In addition to @Barry's answer, you can set endpoint path more specifically:

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
});
Stinko answered 9/12, 2018 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.