Node JS如何将请求数据与请求数据一起POST到另一个服务器/ api

我想从我的节点JS应用程序发布到另一个REST API的图像。 我有在由Node JS读取的Mongo DB中的图像(作为二进制数组数据),然后应该被发送到另一个API。

我面临的问题是如何随图像一起发送请求数据? 我有这个原始数据(这是在JSON格式),应该与图像一起POST:

{"data":{"client":"abc","address": "123"},"meta":{"owner": "yourself","host": "hostishere"}} 

我需要使用“请求”模块来做到这一点。 如果能帮助更好的话,我可以使用'multer'。 但是,我坚持如何发送上述请求数据与图像stream一起。 以下是我目前的代码。 你能帮我完成吗?

  var options = { host: 'hostname.com', port: 80, path: '/api/content', method: 'POST', headers:{ 'Content-Type' : 'multipart/form-data' } }; var request = http.request(options, function(response) { var str = ''; var respTime =''; response.on('data', function (chunk) { str = str.concat(chunk); }); response.on('end', () => { console.log('No more data in response.'); }); setTimeout(function() { res.send(JSON.stringify( { 'imageURL': IMG_URL, 'imageId': IMG_ID, 'body': JSON.parse(str) } )); }, 1000); }); request.on('error', (e) => { console.error('**** problem with request: ', e); }); request.write(image.IMG_STR); //image.IMG_STR is the binary array representation of the image. request.end(); 

更新:06/06/2017

所以,我碰巧与提供端点的REST团队交谈,发现数据应该以下面的特定格式发送。 以下是成功请求的快照。 有人可以帮我使用我应该使用的节点代码吗? 我已经尝试过表单数据包,但一直得到相同的错误: 邮差快照

如果您也可以控制“其他API”,则可以将该图像作为二进制数据的base64表示forms包含在后体中(并将其解码到API侧)

回答更新06/06/2017:

根据屏幕截图,API需要multipart / formdata。 https://github.com/request/request#multipartform-data-multipart-form-uploads中logging了具有“request”模块的请求

快速示例(未testing):

 var formData = { Data: {data: {client: "abc" ...}, file: fs.createReadStream('testImage_2.jpg'), }; request.post({url:'<YourUrl>', formData: formData}, function optionalCallback(err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); 

如果使用JSON数据将body添加到请求中,则应该能够发送它:

  var options = { host: 'hostname.com', port: 80, path: '/api/content', method: 'POST', headers:{ 'Content-Type' : 'multipart/form-data' }, body: { "data": {"client":"abc","address": "123"}, "meta":{"owner": "yourself","host": "hostishere"} } }; 

我不明白的是,当没有resvariables定义在任何地方时,为什么你有一个res.send setTimeout