2

App.js

const bodyParser = require('body-parser');

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

Background

I am currently rendering a C3.js chart in a webpage. I need to have the image representation of that chart so I can display it in other ways throughout my app. In order to do that I am converting the SVG to canvas with html2canvas and then converting that to a blob which I then post to an express server.

When I check the network tab I can see the blob is in the payload section. But, on the server when I console.log(req.body) it outputs an empty object {}.

Example

Client Side

function setImage() {
  html2canvas(document.querySelector('#chart')).then(canvas => {
    canvas.toBlob(
      function(blob) {
        const url = 'http://localhost:3000/api/v1/pdf';

        fetch(url, {
          method: 'POST',
          headers: {},
          body: blob,
        })
          .then(response => response.json())
          .then(success => console.log(success))
          .catch(error => console.log(error));

        console.log(blob);
      },
      'image/jpeg',
      1,
    );
    document.body.appendChild(canvas);
  });
}

Server Side

router.post('/', (req, res, next) => {
  console.log(req.body);

  res.json({ message: 'Something good happened' });
});

Things I have tried

JSON.stringify(blob)

Different headers but I also read that leaving it blank should also work,

headers: new Headers({ 'Content-Type': 'application/json' })

In the network tab from chrome dev tools

enter image description here

The terminal output from the express route

enter image description here

When I console.log(blob) it looks like an object,

enter image description here Question

What is the proper way to POST the blob and verify that I have access to it on the server?

brimble2010
  • 16,218
  • 7
  • 26
  • 42
wuno
  • 8,388
  • 15
  • 72
  • 163
  • 1
    [req.body Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.](https://expressjs.com/en/api.html#req.body) — Your code is missing any sign of a middleware parser. Do you have one? Provide a [mcve]. – Quentin May 09 '18 at 14:48
  • usually string should be fine for body, but try to wrap it in JSON like: `body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json' })` – Domenik Reitzner May 09 '18 at 14:53
  • 1
    @DomenikReitzner — A [blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) is not a string. – Quentin May 09 '18 at 14:56
  • @wuno — It is an issue with body parser. Presumably, none of the other routes are trying to process a raw file. See the duplicate question. – Quentin May 09 '18 at 15:52
  • Anyone else stumbling here can refer to this answer: https://stackoverflow.com/questions/18710225/node-js-get-raw-request-body-using-express?noredirect=1&lq=1 – John Galt Dec 15 '19 at 15:24

0 Answers0