简体   繁体   中英

TypeError: Cannot read property 'send' of undefined : NodeJs

I have installed below node js package and using to send sms from our project:

npm install springedge

Now, I am using below code as file send_messages.js

var springedge = require('springedge');

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

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

But While running send_messages.js I am getting error as below:

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

I have tried coping the library file into root folder/same directory but error remain same. I have received some warning while installation of this package but all of them where optional so i skipped that.

Note: I have checked all the "Similar questions", Most of are related to angular js and very few are related to nodejs which are different.

The issue is that the documentation from the project are wrong, and you have been misled.

To fix this, you have invoke the function that springedge exports, like so:

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

As per requested in comments, I've modified the source package to not require invoking a function:

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);
    }
  }
}

The new API is as follows:

var springedge = require('springedge');

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

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

Optionally pass a timeout parameter to the springedge.messages.send method to override the default ( 5000 ms):

var springedge = require('springedge');

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM