1

I am using Express.js to create api and validating it through express-validator, I'm trying to send a large amount of data which consists of an array with more than 2000 objects in it. You can create the array as

const ids = Array(2000)
  .fill(0)
  .map((_, index) => {
    return {
      "A": "1",
      "B": "2",
      "C": "0",
      "D": "MO",
      "E": "1",
      "F": "0",
      "G": "XYZ",
      "H": "000",
      "I": "999"
    };
  });

And I'm calling the api using axios.

axios.post('/demo', {
  d:ids,
});

And this is my api

app.post('/demo', async (req, res, next) => {
    console.log(req.body);
    const errors = validationResult(req);
    console.log('---- errors', errors);
    res.end('hello world');
  }
);

Now when I log req.body it shows empty object {}. Is this because express is not able to read this array or is there anything which I'm doing wrong.

beingyogi
  • 1,316
  • 2
  • 13
  • 25
  • Do you have appropriate Express middleware to parse the body and populate `req.body`? By default, Express does not read the body and thus nothing is put in `req.body`. If you're sending JSON then you would want `app.use(express.json())` before your route handler. – jfriend00 Sep 01 '20 at 06:04

1 Answers1

0

try this in your server.js or app.js before app.post

express.json() is a method inbuilt in express to recognize the incoming Request Object as a JSON Object. This method is called as a middleware in your application using the code:

app.use(express.json())

express.urlencoded() is a method inbuilt in express to recognize the incoming Request Object as strings or arrays. This method is called as a middleware in your application using the code:

app.use(express.urlencoded());

for more explanation refer this

Also one the possibility is that the default size limit may have exceeded. So in that case you can manually set the request size limit.

app.use(express.json({limit:'2mb'}))

for more explanation refer this

beingyogi
  • 1,316
  • 2
  • 13
  • 25
Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67
  • I think the request size limit was been exceeded so by adding `app.use(express.json({ limit: '2mb' }));` solved my issue – beingyogi Sep 01 '20 at 12:20
  • That's good if it worked, thank you for the update, feel free to edit my answer and add the limit size to the code so that it helps anybody else for the future, and if you can accept this as an answer to your solution would be great :) – Jatin Mehrotra Sep 01 '20 at 13:25