Vallo
Vallo

Reputation: 1967

Parse JSON from body when header is wrongly set

I'm using express.js to receive a JSON from a server that wrongly set the encoded header as urlencoded.

Content-Type: application/x-www-form-urlencoded\r\n

As I try to parse it I get different errors, such as "TypeError: Cannot convert object to primitive value".

If I send the JSON using postman with the correct header it works flawlessly.

How can I parse this JSON?

Upvotes: 1

Views: 83

Answers (1)

lilezek
lilezek

Reputation: 7344

I wouldn't use body-parser.

If you do, it will try to decode your body according to the http headers.

Instead, you could write your own middleware, which can be something similar to this:

app.use((req, res, next) => {
    req.body = JSON.parse(req.read());
    next();
})

Upvotes: 1

Related Questions