Reputation: 57
I am trying to send an audio as a Blob object in React with Typescript to the server with Axios. I have been trying many ways but I always get an emty object on the node server.
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
{ test: 'test' }
I do receive it correctly on the server.
Upvotes: 3
Views: 5073
Reputation: 10009
As you are sending the data in multipart
, you need to listen to the data
event to get the body data. If I am sending {foo: bar}
as data, I can get it like:
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. This would give you the data in your req.body
object.
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
.
Upvotes: 3