TypeError:无法读取undefined:NodeJs的属性'send'

时间:2017-07-12 13:44:12

标签: node.js npm

我安装了以下节点js包并用于从我们的项目中发送短信:

npm install springedge

现在,我使用下面的代码作为文件send_messages.js

var springedge = require('springedge');

var params = {
  'apikey': 'xxxxxxxxxxxx', //API key provided by springedge.com
  'sender': 'SEDEMO', //Test Sender
  'to': [
    '919035732236'  //Test Numberss
  ],
  'body': 'test+message'
};

springedge.messages.send(params, function (err, response) {
  if (err) {
    return console.log(err);
  }
  console.log(response);
});

但是在运行send_messages.js时我收到如下错误:

springedge.messages.send(params, function (err, response) {
                   ^

    TypeError: Cannot read property 'send' of undefined
        at Object.<anonymous> (/var/www/html/xxxxx/node_modules/springedge/send_messages.js:14:20)
        at Module._compile (module.js:410:26)
        at Object.Module._extensions..js (module.js:417:10)
        at Module.load (module.js:344:32)
        at Function.Module._load (module.js:301:12)
        at Function.Module.runMain (module.js:442:10)
        at startup (node.js:136:18)
        at node.js:966:3

我尝试将库文件复制到根文件夹/同一目录但错误保持不变。我在安装此软件包时收到了一些警告,但所有这些都是可选的,所以我跳过了它。

注意:我已经检查了所有“类似问题”,大多数都与角度js有关,很少与nodejs有关。

1 个答案:

答案 0 :(得分:2)

问题是项目的文档是错误的,而且你被误导了。

要解决此问题,您可以调用springedge导出的函数,如下所示:

var springedge = require('springedge')();

根据评论中的要求,我已将源包修改为不需要调用函数:

lib/springedge.js

/**
 * SpringEdge API methods
 *
 * @module springedge
 */

var http = require('https');
var querystring = require('querystring');
var ospath = require('path');
var root = ospath.resolve('.');
var pkg = require(root + '/package.json');

/**
 * httpRequest does the API call
 * and process the response
 *
 * @param {String} method
 * @param {String} path
 * @param {Object} params
 * @param {Integer} timeout
 * @param {Function} callback
 * @return {Void}
 */
function httpRequest(method, path, params, timeout, callback) {
  var options = {};
  var complete = false;
  var body = null;
  var request;

  if (typeof params === 'function') {
    callback = params;
    params = null;
  }

  /**
   * doCallback prevents multiple callback
   * calls emitted by node's http module
   *
   * @param {Error} err
   * @param {Mixed} res
   * @return {Void}
   */
  function doCallback(err, res) {
    if (!complete) {
      complete = true;
      callback(err, res || null);
    }
  }

  // build request
  options = {
    hostname: 'instantalerts.co/api/web',
    path: path,
    method: method,
    headers: {
      'User-Agent': 'SpringEdge/ApiClient/' + pkg.version + ' Node.js/' + process.versions.node
    }
  };

  if (options.method === 'POST' || options.method === 'PUT' || options.method === 'GET') {
    body = JSON.stringify(params);
    options.headers['Content-Type'] = 'application/json';
    options.headers['Content-Length'] = Buffer.byteLength(body, 'utf8');
  } else {
    options.path += params ? '?' + querystring.stringify(params) : '';
  }

  request = http.request(options);

  // set timeout
  request.on('socket', function (socket) {
    socket.setTimeout(parseInt(timeout, 10));
    socket.on('timeout', function () {
      request.abort();
    });
  });

  // process client error
  request.on('error', function (e) {
    var error = new Error('request failed');

    if (error.message === 'ECONNRESET') {
      error = new Error('request timeout');
    }

    error.error = e;
    doCallback(error);
  });

  // process response
  request.on('response', function (response) {
    var data = [];
    var size = 0;
    var error = null;

    response.on('data', function (ch) {
      data.push(ch);
      size += ch.length;
    });

    response.on('close', function () {
      doCallback(new Error('request closed'));
    });

    response.on('end', function () {
      data = Buffer.concat(data, size)
        .toString()
        .trim();

      try {
        data = JSON.parse(data);
        if (data.errors) {
          error = new Error('api error');
          error.statusCode = response.statusCode;
          error.errors = data.errors;
          data = null;
        }
      } catch (e) {
        error = new Error('response failed');
        error.statusCode = response.statusCode;
        error.error = e;
        data = null;
      }

      doCallback(error, data);
    });
  });

  // do request
  request.end(body);
}

// METHODS
module.exports = {
  messages: {
    /**
     * Send a text message
     *
     * @param {Object} params
     * @param {Integer} timeout
     * @param {Function} callback
     * @return {void}
     */
    send: function (params, timeout, callback) {
      if (timeout instanceof Function) {
        callback = timeout;
        timeout = 5000;
      }
      if (params.recipients instanceof Array) {
        params.recipients = params.recipients.join(',');
      }

      httpRequest('GET', '/send/', params, timeout, callback);
    }
  }
}

新API如下:

var springedge = require('springedge');

var params = {
  'apikey': '636n033l3549o14yp1ljdti3t81rk11v5', //TEST API Key
  'sender': 'SEDEMO', //Test Sender
  'to': [
    '919035732236'  //Test Numberss
  ],
  'body': 'test+message'
};

springedge.messages.send(params, function (err, response) {
  if (err) {
    return console.log(err);
  }
  console.log(response);
});

可选择将timeout参数传递给springedge.messages.send方法以覆盖默认值(5000 ms):

var springedge = require('springedge');

var params = {
  'apikey': '636n033l3549o14yp1ljdti3t81rk11v5', //TEST API Key
  'sender': 'SEDEMO', //Test Sender
  'to': [
    '919035732236'  //Test Numberss
  ],
  'body': 'test+message'
};

springedge.messages.send(params, 3000, function (err, response) {
  if (err) {
    return console.log(err);
  }
  console.log(response);
});