1

I've been struggling to parse the request body from POST. I tested the code locally via curl and returns the json body. On Lambda, I tried both curl and Postman but it just returned the buffer data.

Basically, I can't manipulate the data.

index.js

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const serverless = require('serverless-http');

const app = express();
app.use(express.json());
// app.use(bodyParser.json());

// Routes
app.use('/db', require('./routes/db'));

module.exports.handler = serverless(app);

routes > db.js

const express = require('express');
const { Pool } = require('pg');
const router = express.Router();

// Test
router.post('/test', (req, res) => {
  console.log('Raw req.body:', req.body);
  res.json({ received: req.body });
});


module.exports = router;

Sample request:

{
  "movetype": 1
}

This is the response using Postman:

{
    "received": {
        "type": "Buffer",
        "data": [
            123,
            13,
            10,
            32,
            32,
            34,
            109,
            111,
            118,
            101,
            116,
            121,
            112,
            101,
            34,
            58,
            32,
            49,
            13,
            10,
            125,
            13,
            10
        ]
    }
}
1
  • 1
    To add, header has "content-type": "application/json". Commented Aug 2 at 9:01

1 Answer 1

1

The problem is that you're most likely using latest body-parser with Express 5, which causes conflict with serverless-http you're also using.

see:

body-parser middleware not triggering in Express 5/body-parser 2.x #274

Parser does not work in serverless environment #608

Suggested workaround is to convert body to JSON when it's a buffer on your own.

see:

Buffer in request.body #297

export const handler = serverless(app, { request: (req) => { if (Buffer.isBuffer(req.body)) { try { req.body = JSON.parse(req.body.toString()); } catch (e) { console.error('Failed to parse body as JSON', e); } } }, })

2
  • 1
    This works. Thanks man! Commented Aug 3 at 14:22
  • great. if the answer solves your problem you can accept it
    – traynor
    Commented Aug 3 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.