Search code examples
javascriptnode.jsexpressbody-parserjqxhr

receiving inflated response from body-parser in express app


Fully working example:

I'm sending some binary data from front-end:

fetch("http://localhost:8081/api", {
  "headers": {
    "accept": "*/*",
    "accept-language": "en-US,en;q=0.9,hr-HR;q=0.8,hr;q=0.7,es-US;q=0.6,es;q=0.5",
    "content-type": "application/octet-stream",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
  },
  "body": "[{\"id\":\"NiDBzAiEWRHo6dsfw\",\"classIndex…\u00020š\u0002points…\u0002[39,4§\u000241³\u00022³\u00023³\u00024³\u00025³\u00026³\u00027³\u00028³\u0002²\u00025§\u00025·\u00025¹\u00025»\u00025½\u00025¿\u00025Á\u00025Ã\u00025Å\u00025²\u00023Ì\u0002,Ü\u0002»\u0002Ü\u0002½\u0002Ü\u0002¿\u0002Ü\u0002Á\u0002Ü\u0002Ã\u0002Ü\u0002Å\u0002Ü\u0002Û\u00026§\u000236·\u0002ï\u0002¹\u0002ï\u0002à\u00026â\u00026ä\u00026æ\u00026è\u00026ê\u00026Û\u00027î\u00027ñ\u00027ó\u00027½\u0002ü\u0002¹\u0002ü\u0002»\u0002ü\u0002‰\u00037¿\u0002ü\u0002Á\u0002ü\u0002Ã\u0002ü\u0002Å\u0002ü\u0002²\u0002þ\u0002§\u0002þ\u0002·\u0002þ\u0002‹\u00038\u00038‰\u00038‘\u00038“\u00038•\u00038—\u00038™\u00039›\u00039\u00039¹\u00029ö\u0002,´\u0003¿\u0002´\u0003Á\u0002´\u0003Ã\u0002´\u0003Å\u0002´\u0003²\u00029‚\u0003¶\u0003„\u0003Ã\u0003³\u00037»\u0002Á\u0003½\u0002Á\u0003¸\u00037º\u00037¼\u00037¾\u00037²\u000212Ç\u0003,Õ\u0003ˆ\u0003Ø\u0003Ö\u0003¿\u0002Ù\u0003Á\u0002Ù\u0003Ã\u0002Ù\u0003Å\u0002Ù\u0003Ô\u000328§\u0002Õ\u00038·\u00021Ö\u0002»\u0002ì\u0003Ú\u0003ï\u0003Ý\u0003Ö\u0002ß\u0003Ö\u0002á\u0003Ö\u0002ã\u0003Ö\u0002Ô\u0003Ø\u0002è\u0003Ø\u0002ë\u0003Ø\u0002¹\u0002ì\u0003 \u0003Ø\u0003®\u0003ã\u0003®\u0003Ô\u0003°\u0003è\u0003°\u0003ë\u0003°\u0003€\u0004°\u0003î\u0003°\u0003½\u00021°\u00035]}]",
  "method": "POST",
  "mode": "cors",
  "credentials": "omit"
});

Receiving it on the back-end:

const bodyParser = require("body-parser");
const express = require("express");
const cors = require("cors");

const octetStreamParser = bodyParser.raw({
  inflate: false,
  type: "application/octet-stream",
  limit: "200mb",
});

const app = express();
app.use(cors());

app.post("/api", octetStreamParser, (req, res) => {
  console.log(req.body.buffer);
  const bufferString = Buffer.from(req.body.buffer).toString();
  console.log(bufferString);
  res.json({ status: "success" });
});

app.listen(8081, () => {
  console.log("Server", `Server is listening on port 8081`);
});

Buffer is inflated with some random code even though I have set inflate: false. What am I missing here? I have sent 445 bytes over the wire from front-end, but I am receiving a fixed size 8192 byte response each time.

Maybe it's worth mentioning that inflation seems to happen each time that request is smaller than x bytes. I think it's about 1-2k bytes, not sure.


Solution

  • Fix is embarrassingly easy, use req.body instead of req.body.buffer. Explanation here.