2016-09-17 36 views
3

我試圖實現sails作爲中間服務器,但我無法通過Sails服務器進行api調用。它適用於成功的api調用,但在Api調用失敗時不起作用。 它給出了這個錯誤。Sails錯誤:undefined不是函數

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) 

這裏是我的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'); 
    } 

}; 

我已經實現了錯誤的功能,但它沒有定義它顯示。我現在無法調試它。

回答

3

這是因爲你在error callBack裏面使用這個,其中引用改變了所以this.error沒有定義。爲了做到這一點,在 一些變量中存儲這個參考,並使用該變量而不是這個。

var protocol = 'http'; 
var self = this; 
var success = function(response){ 
    return res.ok(response); 
}, 
error = function(err){ 
    self.error(res,err); 
}; 
相關問題