Reputation: 13
I am working on a nodejs project which needs to get a response by making a POST request to the API in which I need to send an audio file (audio.ogg) in the body of request. In 'postman' we can do something like this by selecting the file from local and make request.
How can I do the same with my Nodejs application using an npm package like 'request'?
My code so far is quoted here:
var request = require('request');
var fs = require('fs');
var path = require('path');
router.get('/', function(req, res, next) {
var options = {
method: 'post',
body: {
'language': "<language>",
'audio_file':path.join(__dirname, 'audio.ogg')
}, // Javascript object
json: true,
url: "<API>",
headers: {
'Authorization': "<token>",
'ContentType': "application/x-www-form-urlencoded"
}
}
request(options, function (err, res, body) {
if (err) {
console.log('Error :', err)
return
}
console.log(' Body :', body)
});
// res.render('index', { title: 'Express' });
});
Upvotes: 1
Views: 1053
Reputation: 555
In options.headers
, since you're sending binary data, your ContentType should be "multipart/form-data" instead of "application/x-www-form-urlencoded" as binary data is noted to be inefficient to transfer using x-www-form-urlencoded
(see this SO answer for details on why).
Luckily, the request
library you are already using includes the form-data
library for handling multipart/form-data
requests. request
provides the formData
option for this, which you would use instead of using the body
option.
Your updated options object might look something like this:
var formData = {
// Pass a simple key-value pair
language: '<language>',
// Pass data via Streams
my_file: fs.createReadStream(__dirname + '/audio.ogg')
};
var options = {
method: 'post',
formData: formData,
url: "<API>",
headers: {
'Authorization': "<token>",
'ContentType': "multipart/form-data"
}
}
For more info, check the documentation for request
here
Upvotes: 1