我正在尝试将图像从 Node JS 应用程序发布到另一个 REST API。我在 Mongo DB 中有图像(作为二进制数组数据),由 Node JS 读取,然后应该发布到另一个 API。
我面临的问题是如何将请求数据与图像一起发送?我有这个原始数据(JSON 格式),应该与图像一起发布:
{"data":{"client":"abc","address": "123"},"meta":{"owner": "yourself","host": "hostishere"}}
我需要使用“请求”模块来执行此操作。如果有更好的帮助,我可以使用“multer”。但是,我陷入了如何将上述请求数据与图像流一起发送的问题。下面是我当前的代码。你能帮我完成它吗?
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
So, I happened to talk to the REST team that provides the end point and found out that the data should be sent in the following specific format. Below is a snapshot of the request that succeeded. Could someone help me with the Node code that I should use? I have tried form-data package but have been getting the same error: