bobarillo
bobarillo

Reputation: 173

How to make multipart form api requests with requestjs and nodejs?

Trying to interact with the phaxio api using multipart form data. As per the request.js docs for making a post request I do

var request = require('request');

var options = {
    uri: 'https://api.phaxio.com/v1/send',
    headers: {'content-length':'0'}
};

var r = request.post(options);

var form = r.form();

form.append('api_key', '1234');
form.append('api_secret', '1234');
form.append('to', '1234');

r.on('response', function(chunk){
    console.log(chunk);
});

The response body I get from the r.on method is here http://pastie.org/private/wshbn9esendccrkoreeiow I'm unsure how I can see the api response body from the server after submitting the form data. Something like

{
    "success": true,
    "message": "Fax Sent!"
}

Upvotes: 0

Views: 1090

Answers (1)

hexacyanide
hexacyanide

Reputation: 91799

The method request.post() returns a readable stream. Just read the response:

var res = '';
r.on('data', function(data) {
  res += data;
});
r.on('end', function() {
  console.log(res);
});

You can also pipe the response to another writable stream:

var fs = require('fs');
var writable = fs.createWriteStream('/file');
r.pipe(writable);

Upvotes: 1

Related Questions