I'm trying to send as formData
, a stream from an image I get using request
The problem is that the request is fire after the formData
request.
Is there any way I can pipe the image request to recognize? but with the freedom of adding parameters to the formData
?
e.g:
var req = request({
method: 'POST',
url: 'http://www.foo.bar/api/v1/tag/recognize',
formData: {
image_file: request('http://visual-recognition-demo.mybluemix.net/images/horses.jpg'),
param2: 'value2'
},
json: true,
});
How do I fire:
request('http://visual-recognition-demo.mybluemix.net/images/horses.jpg')
so the response can be used in req
UPDATE: Seems like the Content-Length
header is missing in the
http://visual-recognition-demo.mybluemix.net/images/horses.jpg response
and you only get Transfer-Encoding: chunked
More details here
Take a look this part of the docs. What you're describing is essentially this block
request.get('http://google.com/img.png').pipe(request.put('some_url'));
Note the docs
When doing so, content-type and content-length are preserved in the PUT headers.
Also note, request will always return a Stream if you don't specify a callback. If you do provide a callback it tries to convert the response to a String. Use the encoding:null
to get it to return raw bytes.
Example -
request({
url: 'some_url', //your image
encoding: null //returns resp.body as bytes
}, callback..)
To chain calls together (run one after the other) , you can nest the callbacks or use promises. For example to run a request after another request completes -
var request = require('request');
//1st
request('first_url', function (error, response, body) {
if (!error && response.statusCode == 200) {
//2nd
request('other_url', function (error, response, body) {
//process resp
});
}
});
Or even better, convert the request callback code to Promises. See a promise library like Bluebird on how to do this.
Here's an example with bluebird (uses then to work in an iterative fasion)
var Promise = require("bluebird");
Promise.promisifyAll(require("request"));
request.getAsync('some_url').then(function(resp) {
request.getAsync('some_other_url').then(..processing code..);
});