0

整个想法是在 unix 套接字上使用 LXD RESTful API 进行本地操作。以下代码对于每 2 或 3 个错误运行良好一次。我不知道是否与node.js有关或与lxd api有关。

有错误的输出

请求问题:写 EPIPE { [错误:写 EPIPE] 代码:'EPIPE',errno:'EPIPE',系统调用:'write',地址:未定义}

编码:

/*
Adapted from 
http://rapiddg.com/blog/calling-rest-api-nodejs-script
*/
var querystring = require('querystring');
var http = require('http'), req, response;

var socketUSD='/var/lib/lxd/unix.socket';

function RestConsume(){ };

RestConsume.prototype._doRequest_=function(httpMethod,pathAPI,data,fnCallBack){
        var dataString = JSON.stringify(data);
        var headers = {};

        if (httpMethod==='GET'){
            pathAPI+='?'+querystring.stringify(data);

        }else{
            headers = {
              'Content-Type': 'application/json',
              'Content-Length': dataString.length
            };
        }
        var options = {
                socketPath: socketUSD,
                path: pathAPI,
                method: httpMethod,
                headers: headers
            };

        var req=http.request(options, function (res){
            res.setEncoding('utf-8');

            var resultString="";

            res.on('data',function(data){
                resultString +=data;
            });//end res.on('data')//

            res.on('end',function(){
                console.log(resultString);
                var responseObject = JSON.parse(resultString);
                fnCallBack(resultString);
            });
        });

        req.write(dataString);
        req.end();
        req.on('error', function(e) {
            console.log('Haciendo '+httpMethod);
          console.log('problem with request: ' + e.message);
          console.log(e);
        });
};
RestConsume.prototype.doGet=function(pathAPI,data,fnCallBack){
        return this._doRequest_('GET',pathAPI,data,fnCallBack);
};
RestConsume.prototype.doPost=function(pathAPI,data,fnCallBack){
        this._doRequest_('POST',pathAPI,data,fnCallBack);
};
RestConsume.prototype.doPut=function(pathAPI,data,fnCallBack){
        this._doRequest_('PUT',pathAPI,data,fnCallBack);
};
RestConsume.prototype.doDelete=function(pathAPI,data,fnCallBack){
        return this._doRequest_('DELETE',pathAPI,data,fnCallBack);
};
var obj=new RestConsume();
obj.doGet("/1.0/containers/pc01/logs",{},function(data) {
    console.log('get Respuesta:\r\n' + data);
  });
4

1 回答 1

1

固定:使用文档.

更准确地说:

http.request(options, callback).end();

现在,代码就像一个魅力。

于 2015-10-26T23:25:58.697 回答