Sujit Sujit - 2 months ago 23
Javascript Question

Sails Error: undefined is not a function

I am trying to get to implement as middle server but i am unable to get make a 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.

Answer

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