Nodejs get raw data from urlencoded

There are three common ways to set value for Content-Type in a HTTP request: application/x-www-form-urlencoded, application/json, multipart/form-data. Each of them has a different role, and use in different cases.
If you are working on Express and Nodejs, you are very familiar to use the body-parser library to pre-handle a request data especially in POST method. In which case, for example, the client or 3rd party uses application/x-www-form-urlencoded and encoded the body data. At your side, you have to verify, but they encoded it based on raw data. Therefore if you set:

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

then you will never get your goal. Because they are parsing the data to JSON type in the body.
How to get raw data?
Let’s go to inside the body-parser lib, you will see a verify function:

Our purpose to get a Buffer of the raw request body, so we will add this option to urlencoded method
by following:

app.use(bodyParser.urlencoded({
    extended: true,
    verify: (req, res, buf, encoding)=>{
    if (buf && buf.length) {
        req.rawBody = buf.toString(encoding || 'utf8')
    }
   }
}))

Hopefully, it helps you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s