Node JS和Python-从Node JS到Python REST API的POST映像

时间:2018-10-10 08:20:12

标签: python node.js image rest post

我有一个Node JS应用程序。我想将图像从Node JS应用程序发送到以Python编写的REST API。 Python REST API所需的键和输入如下'Image' is the key which the Python API expects

我的问题是我可以用我编写的代码发布一个简单的“ Hello World”字符串,并得到响应。但是,当我尝试发送图像时,出现了问题,并且没有任何响应。

var http = require('http');
var querystring = require('querystring');

// This is some dummy string data
var postData = querystring.stringify({
    msg: 'hello world'
});


var fs = require('fs')
    , path = require('path')
    , certFile = path.resolve(__dirname, 'ssl/client.crt')
    , keyFile = path.resolve(__dirname, 'ssl/client.key')
    , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
    , request = require('request');


// I want to send an image from one server to another. What changes should I make to the options below for POSTing image data
var options = {
    hostname: '127.0.0.1',
    port: 8888,
    path : '/predict',
    //image: fs.createReadStream('car.jpg'),  //Should I give something like this??
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data',
        'Content-Length': postData.length
    }
};

var req = http.request(options, function (res) {
    console.log('STATUS:', res.statusCode);
    console.log('HEADERS:', JSON.stringify(res.headers));

    res.setEncoding('utf8');

    res.on('data', function (chunk) {
        console.log('BODY:', chunk);
    });

    res.on('end', function () {
        console.log('No more data in response.');
    });
});

req.on('error', function (e) {
    console.log('Problem with request:', e.message);
});

req.write(postData);
req.end();

请让我知道我需要对此代码进行哪些更改才能发布图像。我了解了multer包的使用。但是,我遇到的例子都是在两端使用JS。因为对我来说,我拥有Python REST API,所以我不能使用它。请帮忙,因为我已经为此苦苦挣扎了一段时间。

编辑1:基于@Jana的建议,我在选项中添加了multipart并尝试使用,其中image是键,值是fs.createReadStream('car.jpg')。但是,在python端,它没有得到'image'键,因此我得到了False响应。我想念什么?

 var options = {
    hostname: '127.0.0.1',
    port: 8888,
    path : '/predict',
    //image: fs.createReadStream('car.jpg'),  //Should I give something like this??
    multipart: [
        {
            'content-type': 'application/json',
             body: JSON.stringify({'image': fs.createReadStream('car.jpg')          })
        }

    ],
    method: 'POST',
    headers: {
        'Content-Type': 'multipart/form-data',
        //'Content-Length': postImageData.length
    }
};

1 个答案:

答案 0 :(得分:0)

检查此

`request({
    method: 'POST',
    uri: 'http://127.0.0.1:8888/predict',
    multipart: [{
            'content-type': 'application/json',
            body: JSON.stringify({
                "key": "value"
            })
        },
        {
            body: fs.createReadStream('car.jpg')
        }
    ],
},
function(error, response, body) {
    if (error) {
        return console.error('upload failed:', error);
    }
    console.log('Upload successful!  Server responded with:', body);
})`

您也可以从自己的文档Request - Simplified HTTP client

中获得最佳示例