简体   繁体   English

使用Axios将Blob发送到服务器,接收到一个空对象

[英]Send Blob to server with Axios, receiving an empty object

I am trying to send an audio as a Blob object in React with Typescript to the server with Axios. 我正在尝试使用React与Typescript将音频作为Blob对象发送到具有Axios的服务器。 I have been trying many ways but I always get an emty object on the node server. 我已经尝试了许多方法,但是我总是在节点服务器上得到一个emty对象。

As I have seen, now I have what it should be the correct way to do it. 正如我所看到的,现在我已经知道它应该是正确的方法。 But still get an empty object. 但是仍然得到一个空对象。

const config = {
    headers: {
      'Content-Type': 'multipart/form-data; boundary=${data._boundary}'
    }
  };

  try {
    var formData: FormData = new FormData();
    formData.append('audio', audioBlob);

    const res = await axios.post('/api/recording', formData, config);
    console.log(res);
  } catch (err) {
    console.log(err.response.data.errors);
  }

If i do 如果我做

'Content-Type': 'application/json'

and send a normal json for example 并发送一个普通的json例如

{ test: 'test' }

I do receive it correctly on the server. 我确实在服务器上正确接收到它。

As you are sending the data in multipart , you need to listen to the data event to get the body data. multipart发送数据时,您需要侦听data事件以获取主体数据。 If I am sending {foo: bar} as data, I can get it like: 如果我将{foo: bar}作为数据发送,则可以这样获得:

app.use ( '/foo', ( req, res ) => {    
    req.on ( 'data', ( data ) => {
        console.log ( data.toString () );
    } );

    req.on('end', () => {
        res.send('ok');
    });
} );

However, this will give you something like this: 但是,这将为您提供以下信息:

----------------------------807095611705406533847525
Content-Disposition: form-data; name="foo"

bar
----------------------------807095611705406533847525--

This would be difficult to parse. 这将很难解析。 So to ease the parsing, you can use multer . 因此,为了简化解析,您可以使用multer This would give you the data in your req.body object. 这将为您提供req.body对象中的数据。

let multer           = require ( 'multer' );
let processMultipart = multer ( { storage : multer.memoryStorage () } );

app.use ( '/foo', processMultipart.array ( "foo" ), ( req, res ) => {
    console.log ( req.body );
    res.send ( "ok" );
} );

This would give you the output as [Object: null prototype] { foo: 'bar' } and you can access the value as req.body.foo . 这将为您提供[Object: null prototype] { foo: 'bar' } ,您可以访问req.body.foo值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM