Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sails Error: undefined is not a function

I am trying to implement sails as middle server but I am unable to make an api call through Sails server. It works well when for successful api call but it won't work when Api call Failed. it gives this error.

this.error(res,err);
     ^

TypeError: undefined is not a function
    at error (/Users/nitin.tiwari/owner-app-backend/api/controllers/ApiController.js:26:12)
    at IncomingMessage.<anonymous> (/Users/nitin.tiwari/owner-app-backend/api/services/XHR.js:54:11)
    at IncomingMessage.emit (events.js:129:20)
    at _stream_readable.js:908:16
    at process._tickDomainCallback (node.js:381:11)

here is my ApiController.js

/**
 * ApiController
 *
 * @description :: Server-side logic for managing apis
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var config = sails.config;

module.exports = {

  /**
   * @ApiController.ready()
   *
   * Prepare request object and calls XHR.send at the end.
   *
   */
  ready: function(req, res, method, data){
    var options;
    var data = data || '';
    var protocol = 'http';
    var success = function(response){
      return res.ok(response);
    },
    error = function(err){
      this.error(res,err);
    };
      options = {
        hostname: config.api.host,
        path: req.originalUrl,
        method: method,
        headers: {
          'Content-Type': 'application/json'
        }
      }

    console.log(options,data);
    XHR.send(options, data, success, error, protocol);
  },

  /**
   * @ApiController.get()
   *
   * Serves all the get request.
   *
   * Makes XHR to Rails API and reverts the response.
   *
   */
  error:function(res,err){
    if(err.status == 422 && err.error.error.code == 41){
        var obj = {
          id: -1 
        }
        return res.ok(obj);
      }
      return res.apiError(err);
  },

  get: function(req, res){
    return this.ready(req, res, 'GET');
  }

};

I have implemented the error function but it is showing as it is not defined. I am unable to debug it now.

like image 964
Sujit Avatar asked Jun 07 '26 21:06

Sujit


1 Answers

It is because you are using this inside error callBack where the reference of this is changed so this.error is not defined. in order to do that store the reference of this in some variable and use that variable instead of this.

var protocol = 'http';
var self = this;
var success = function(response){
  return res.ok(response);
},
error = function(err){
  self.error(res,err);
};
like image 130
Nitin9791 Avatar answered Jun 09 '26 09:06

Nitin9791



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!