发布blob图像文件以使用javascript fetch表达服务器

时间:2018-05-09 14:46:13

标签: javascript node.js express fetch

App.js

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

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

背景

我目前正在网页中呈现C3.js图表。我需要拥有该图表的图像表示,以便我可以在整个应用程序中以其他方式显示它。为此,我将SVG转换为canvas html2canvas,然后将其转换为blob,然后将其发布到快速服务器。

当我查看网络标签时,我可以看到blob部分中的payload。但是,当我console.log(req.body)时,它会在服务器上输出一个空的object {}

示例

客户端

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);
  });
}

服务器端

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

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

我尝试过的事情

JSON.stringify(blob)

不同的标题,但我也读到将它留空也应该有效,

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

来自chrome dev工具的网络标签

enter image description here

快速路线的终端输出

enter image description here

当我console.log(blob)它看起来像一个物体时,

enter image description here问题

POST blob并验证我是否可以在服务器上访问它的正确方法是什么?

0 个答案:

没有答案